fun interface kotlin 函数式接口(SAM转换)

687 阅读1分钟

1.fun interface 函数式接口

在阅读kotlin三方依赖源码经常发现 fun interface

Call.kt

interface Call : Cloneable {
  
  public override fun clone(): Call

  fun interface Factory {
    fun newCall(request: Request): Call
  }
}

Interceptor.kt 
fun interface Interceptor {
  @Throws(IOException::class)
  fun intercept(chain: Chain): Response

  companion object {
    inline operator fun invoke(crossinline block: (chain: Chain) -> Response): Interceptor =
      Interceptor { block(it) }
  }
  
  Coil
  
fun interface Factory {

    fun create(request: ImageRequest): EventListener

    companion object {
        @JvmField val NONE = Factory { EventListener.NONE }
    }
}

2. 函数式接口或 SAM(单一抽象方法)接口

1.只有一个抽象方法的接口
2.只有单个非默认抽象方法的接口,可以直接用 Lambda 来表示,
前提是 Lambda 所表示的函数类型能够跟接口中的方法签名相匹配

fun interface Runnable {
    fun run()
}


fun setRunnable(runnable: Runnable) {
}

fun main() {
    //不用sam 
    setRunnable(object :Runnable{
        override fun run() {
            
        }
    })
    //使用sam
    setRunnable{
        
    }
}

3.java 函数式接口

jdk 1.8 引入了函数式接口的并引入了新的注解 @FunctionalInterface 使函数式接口具体和规范化

我们最熟悉的Thread(Runnable)

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}
Runnable runnable = ()->{

};