Foggy day

Kotlin - anonymous function 본문

Kotlin

Kotlin - anonymous function

jinhan38 2021. 3. 17. 22:47

 

class KotlinPlayGroundActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin_play_ground)

        val lists = listOf(1, 2, 3, 4, 5, 6, 7)

        println("multiplyMap : ${multiplyMap(lists)} ")
        println("multiplyMapSecond : ${multiplyMapSecond(lists)}")
        println("multiplyFold : ${multiplyFold(lists)} ")
        println("multiplyExtension : ${lists.multiplyExtension()}")
        println("multiplyExtensionSecond : ${lists.multiplyExtensionSecond()}")
        println("multiplyCloser : ${multiplyCloser(lists)}")
        println("multiplyCloserSecond : ${multiplyCloserSecond(lists, count)}")

    }


    fun multiplyMap(list: List<Int>): List<Int> = list.map { a -> a * 3 }

    fun multiplyMapSecond(list: List<Int>): List<Int> = list.map { it * 2 }

    fun multiplyFold(list: List<Int>): Int = list.fold(1) { a, b -> a * b }

    fun List<Int>.multiplyExtension(): Int = this.fold(1) { a, b -> a * b }

    fun List<Int>.multiplyExtensionSecond(): Int = this.fold(1) { a: Int, b: Int -> a * b }


    val count = 3

    fun multiplyCloser(list: List<Int>): List<Int> = list.map { it * count }

    fun multiplyCloserSecond(list: List<Int>, count: Int): List<Int> = list.map { it * count }

}

 

'Kotlin' 카테고리의 다른 글

Kotlin - Kotlin casting, smart cast  (0) 2021.03.19
Kotlin - Elvis, null check  (0) 2021.03.17
Kotlin - extension function, fold, reduce  (0) 2021.03.17
Kotlin - function, expression syntax  (0) 2021.03.16
Kotlin - collection about immutable, mutable  (0) 2021.03.16