What does ".()" mean in Kotlin?
There is a misunderstanding that T.() -> Y is (T.()) -> Y, but actually is T.(()->Y). As we know (X)->Y is a lambda, so T.(X)->Y is an extension on T.
If there is no parameter, the form is T.() -> Y
It's interesting that we can call it in two ways as the blew.
import kotlinx.coroutines.*
open class MyClass(var name: String){
open fun something(){println("myclass something")}
}
fun main() = runBlocking{
val me = MyClass("Boll")
val someMethod: MyClass.(Int) -> String = { n ->
List(n){"X"}.joinToString(separator="", postfix=":${this.name}")
}
val some = me.someMethod(10)
//val some = someMethod(me, 10)
println(some)
val anotherMehtod: MyClass.() -> String = {
"Y:"+this.name
}
//val another = me.anotherMehtod()
val another = anotherMehtod(me)
println(another)
}
this is a good question. so when you have this kind of statement: T.()
it means that in the lamda you will be passing in, "this" (which is the current object) will be of type T. Lets take a look how easy it its to understand:
Lets say we have some class with a function called myFun which takes in a lambda defined like this:
class MyObject {
fun myFun(doSomething: MyObject.()->Unit) {
doSomething()
}
fun doAnotherThing() {
Timber.d("myapp", "doing another thing")
}
}
to call this function i'd do this:
MyObject().myFun { doAnotherThing() }
see how it knew to use the MyObject() reference as the "this". this is really calling this.doAnotherThing() where this is the Myobject() instance just created.
could have also done this:
MyObject().apply{myFun { doAnotherThing() }}
A function that takes in nothing and returns nothing in Kotlin looks like:
var function : () -> Unit
The difference is that the function in your code takes in nothing, returns nothing, but is invoked on an object.
For example,
class Builder (val multiplier: Int) {
fun invokeStuff(action: (Builder.() -> Unit)) {
this.action()
}
fun multiply(value: Int) : Int {
return value * multiplier
}
}
The important bit here is the way we've declared the type of action
action: (Builder.() -> Unit)
This is a function that returns nothing, takes in nothing but is invoked on an object of type Builder
.
This means when we use this builder like so
var builder = Builder(10)
builder.invokeStuff({
var result = multiply(1)
println(result)
})
The context of this
has been set to the builder object and we can invoke functions declared within the builder.
Refer more here.