添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
知识渊博的扁豆  ·  Java ...·  5 月前    · 
聪明的绿茶  ·  mysql 按季度group ...·  11 月前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

Sure, but replacing Any::toString with T::toString won't compile either. I can pass a lambda, but is there a simper way? – Dol.Gopil Sep 10, 2018 at 13:41

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) { 
    // ...

It would have compiled if do like this:

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

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.