Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between lambda and KFunction in Kotlin

Tags:

kotlin

The following does not compile:

fun<T> doSomething(value: T, action: (value: T) -> String = Any::toString){
  //do something
}

The error is:

Kotlin: Type mismatch: inferred type is KFunction1<Any, String> but (T) -> String was expected

Making it work is easy:

fun<T> doSomething(value: T, action: (t: T) -> String = {t -> t.toString()}) = action(value)

However, this leaves me wondering: what is the difference between lambdas and KFunctions? Why do we need both?

Also is there a simpler way to provide Any::toString as the default action?

like image 583
Dol.Gopil Avatar asked Sep 10 '18 13:09

Dol.Gopil


Video Answer


2 Answers

The reason why the code does not compile has nothing to do with the difference between lambdas and KFunctions. It doesn't compile because the parameter needs to be a function of type (T) -> String, and Any::toString is a function of type (Any) -> String.

like image 79
yole Avatar answered Sep 22 '22 00:09

yole


When you obtain any function (lambda or otherwise) reference with :: you are using reflection. KFunction is Kotlin's way to to wrap around reflected functions.

As to making Any::toString work - there is a way but you may not like it:

fun <T> doSomething(value: T, action: (t: T) -> String = Any::toString as (T) -> String) { 
    // ...
}
like image 40
David Soroko Avatar answered Sep 21 '22 00:09

David Soroko