What does "MyType.()" mean in Kotlin?

This expression doesn’t look like a lambda that accepts an Int and returns an Int

lateinit var myVar: Int.() -> Int

What does Int.() mean in Kotlin? How to assign something to myVar?

>Solution :

Kotlin supports the concept of extension functions.

A type definition like Foo.(Bar) -> Baz describes a functional type, that takes an object of type Foo as its receiver, accepts an argument of type Bar and returns an object of type Baz.

This allows to synthetically add extensions to a type that you cannot control. For example, you may add an extension to String and invoke it, like it was defined on the class itself.

fun String.hasEvenLength(): Boolean = this.size % 2 == 0

val result = "foo".hasEvenLength()

The this keyword inside an extension function corresponds to the receiver object (the one that is passed before the dot).

Leave a Reply