Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Functional (SAM) interfaces VS Function types

Tags:

kotlin

With Kotlin 1.4 we now have Functional Interfaces

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

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?.

like image 864
Malcolm J Rosse Avatar asked Nov 28 '25 11:11

Malcolm J Rosse


1 Answers

It's a performance dis-advantage because the lambda is no longer inlined (unless the JIT decides to, but it won't be instant). Even if you mark runBlock as inline, the compiler will warn you that the argument won't be inlined.

There are only two reasons to use fun interfaces instead of function types:

  1. Backwards compatibility when porting code using Java functional interfaces.
  2. Not exposing Kotlin function types in API intended for use from Java.

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. This way you could use lambdas for parameters of those types both in Java and Kotlin code. But if you declared the interface in Kotlin, you could only use lambdas for them in Java.

like image 143
Alexey Romanov Avatar answered Nov 30 '25 05:11

Alexey Romanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!