kotlin学习笔记(SAM)

148 阅读1分钟
SAMSingle Abstract Method,在Java中,对于只有一个方法的接口(`@FunctionalInterface`),我们可以使用lambda进行表示,

​ Kotlin的匿名类表示法:

    val newCachedThreadPool = Executors.newCachedThreadPool()
    newCachedThreadPool.submit(object : Runnable {
        override fun run() {
            println("runnig")
        }
    })

kotlin对于这种只有一个方法的接口的匿名内部类简写形式

    val newCachedThreadPool = Executors.newCachedThreadPool()
    newCachedThreadPool.submit(Runnable {
         println("test")
    })

其实在Kotlin中,这种参数为 只有一个方法的java接口,可以看作接受一个kotlin方法的参数

    val myFun: () -> Unit = {
        println("test")
    }
    val newCachedThreadPool = Executors.newCachedThreadPool()
    newCachedThreadPool.submit(myFun)

即Runnable的public abstract void run();可以看作是类型为() -> Unit的函数。

因此可以简写为下面这种方式

    val newCachedThreadPool = Executors.newCachedThreadPool()
    newCachedThreadPool.submit {
        println("test")
    }

但实际上kotlin的处理方式是把这个kotlin的lambda表达式内联到匿名类里面的,就是包装了一下,并非直接转换

    val newCachedThreadPool = Executors.newCachedThreadPool()
    newCachedThreadPool.submit(object : Runnable{
        override fun run() {
            { println("test") }()
        }
    })