Kotlin学习三:高阶函数

↘锁芯ラ 提交于 2019-11-27 02:41:33

一、高阶函数的基本概念

 

class Hello {
    fun world() {
        println("Hello World")
    }
}

class PdfPrinter {
    fun print(any: Any) {
        kotlin.io.print(any)
    }
}

fun main(args: Array<String>) {
    val mList: List<Int> = listOf(1, 3, 5, 7, 9)
    println(mList)

    val mList2: List<String> = arrayListOf("1", "2", "5")
    println(mList2)

    val mArray: Array<String> = arrayOf("2", "5", "8")
    mArray.forEach { print(it) }
    println()
    mArray.forEach(::print)
    println()

    Hello::world
    val helloWorld = Hello::world
    println(helloWorld)

    val hello = Hello()
    hello.world()

    mArray.filter(String::isNotEmpty)

    val pdfPrinter = PdfPrinter()
    mArray.forEach (pdfPrinter::print)
}

二、常见高阶函数

1、关于list映射

fun main(args: Array<String>) {
    javaMethodWriting()
    println()
    kotlinMethodWriting()
}

fun kotlinMethodWriting() {
    val list = listOf(1, 2, 3, 4)

    val newList = list.map {
        it * 2 + 1
    }

    val newList2 = list.map {
        it.toDouble()
    }

    val newList3 = list.map(Int::toDouble)

    newList.forEach(::print)
    println()
    newList2.forEach(::print)
}

fun javaMethodWriting() {
    val list = listOf(1, 2, 3, 4)

    val newList = ArrayList<Int>()

    list.forEach {
        val newElement = it * 2 + 1
        newList.add(newElement)
    }

    newList.forEach(::print)
}

 

三、

四、

五、

六、

七、

八、

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!