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.
Lambda expression is a simplified representation of a function. It can be passed as a parameter, stored in a variable or even returned as a value. Note: If you are new to Android app development or just getting started, you should get a head start from Kotlin for Android: An Introduction.
Being anonymous, lambda functions can be easily passed without being assigned to a variable. Lambda functions are inline functions and thus execute comparatively faster. Many times lambda functions make code much more readable by avoiding the logical jumps caused by function calls.
Higher-Order Function – In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas.
:: converts a Kotlin function into a lambda. this translates to MyClass(x, y) in Kotlin.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With