gpt4 book ai didi

Kotlin - 函数式 (SAM) 接口(interface) VS 函数类型

转载 作者:行者123 更新时间:2023-12-02 12:17:14 25 4
gpt4 key购买 nike

在 Kotlin 1.4 中,我们现在有了函数式接口(interface)

fun interface Todo {
fun run()
}

fun runBlock(todo: Todo){
if(condition)
todo.run()

}

fun runBlock{
println("Hello world")
}

之前我总是使用 (T) -> T

inline fun runBlock(block: ()-> Unit){
if(condition)
block()
}

fun runBlock{
println("Hello world")
}

所以基本上我可以用这两种方法完成相同的任务,使用函数式 SAM() 接口(interface)比函数类型有任何性能优势吗?

最佳答案

这是一个性能dis优势,因为 lambda 不再是内联的(除非 JIT 决定这样做,但它不会是即时的)。即使您将 runBlock 标记为 inline,编译器也会警告您该参数不会被内联。

使用有趣的接口(interface)而不是函数类型只有两个原因:

  1. 使用 Java 功能接口(interface)移植代码时的向后兼容性。
  2. 不在旨在从 Java 使用的 API 中公开 Kotlin 函数类型。

要扩展第 1 点:在 Kotlin 1.4 之前,建议将功能接口(interface)保留为 Java 代码,即使所有其他代码都是 Kotlin。这样您就可以在 Java 和 Kotlin 代码中对这些类型的参数使用 lambda。但是,如果您在 Kotlin 中声明接口(interface),则只能在 Java 中为它们使用 lambda。

关于Kotlin - 函数式 (SAM) 接口(interface) VS 函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64409514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com