简体   繁体   English

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

[英]Kotlin - Functional (SAM) interfaces VS Function types

With Kotlin 1.4 we now have Functional Interfaces在 Kotlin 1.4 中,我们现在有了函数式接口

fun interface Todo {
       fun run()
}

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

}

fun runBlock{
   println("Hello world")
}

Before i was always using (T) -> T在我总是使用 (T) -> T 之前

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

fun runBlock{
   println("Hello world")
}

So basically I can make the same task with both methods , there is any performance advantage by using Functional SAM() Interfaces over Function Type?.所以基本上我可以使用这两种方法完成相同的任务,通过使用 Functional SAM() Interfaces over Function Type 有任何性能优势吗?。

https://kotlinlang.org/docs/reference/whatsnew14.html#sam-conversions-for-kotlin-interfaces https://kotlinlang.org/docs/reference/whatsnew14.html#sam-conversions-for-kotlin-interfaces

the compiler automatically converts the lambda to an instance of the class that implements the abstract member function.编译器会自动将 lambda 转换为实现抽象成员函数的类的实例。

So, no performance advantage, it's the same thing as before.所以,没有性能优势,和以前一样。 The compiler now does what you had to do before.编译器现在做你以前必须做的事情。

It's a performance dis -advantage because the lambda is no longer inlined (unless the JIT decides to, but it won't be instant).这是一个性能DIS -advantage因为拉姆达不再内联(除非JIT决定,但它不会是瞬间)。 Even if you mark runBlock as inline , the compiler will warn you that the argument won't be inlined.即使您将runBlock标记为inline ,编译器也会警告您该参数不会被内联。

There are only two reasons to use fun interfaces instead of function types:使用 fun 接口而不是函数类型的原因只有两个:

  1. Backwards compatibility when porting code using Java functional interfaces.使用 Java 功能接口移植代码时的向后兼容性。
  2. Not exposing Kotlin function types in API intended for use from Java.未在 API 中公开供 Java 使用的 Kotlin 函数类型。

To expand on point 1: before Kotlin 1.4 it was advised to keep functional interfaces as Java code, even if all your other code was Kotlin.扩展第 1 点:在 Kotlin 1.4 之前,建议将函数式接口保留为 Java 代码,即使所有其他代码都是 Kotlin。 This way you could use lambdas for parameters of those types both in Java and Kotlin code.通过这种方式,您可以在 Java 和 Kotlin 代码中对这些类型的参数使用 lambda。 But if you declared the interface in Kotlin, you could only use lambdas for them in Java.但是如果你在 Kotlin 中声明了接口,你就只能在 Java 中为它们使用 lambdas。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM