简体   繁体   中英

Is it good to extend lambdas in kotlin

I'm relatively new in kotlin programming, and recently I found out that this is a valid statement:

class Test : (Int) -> String {
    override fun invoke(p1: Int): String {
        return p1.toString()
    }
}

When I see it I have a feeling that it might be not very good programming practice to extend Lambdas, however I don't have any objective reasons to think so. I haven't found any docs regarding the issue, so could you please advise if it is good or bad to extend lambdas.

The function types like (Int) -> String are technically interfaces (as described in this detailed spec doc ), so if you feel the need to implement them in your classes, there's nothing to stop you from doing so.

If you do so, you'll be able to use instances of your class where (Int) -> String and Int.() -> String functions are expected.

If you only need to invoke instances of your class with the function syntax but not to use them as instances of function types, it is enough to just define the invoke(...) operator as a member or an extension function.


UPD: In Kotlin 1.4 another way to clearly describe the semantics of API that receives a function is functional interfaces . Using them, you define an interface marked as fun , and the caller may either pass a lambda or implement your interface directly. Before Kotlin 1.4, such a conversion on the call site was only available for Java interfaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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