Home > Software engineering >  What does "MyType.()" mean in Kotlin?
What does "MyType.()" mean in Kotlin?

Time:01-10

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?

CodePudding user response:

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

CodePudding user response:

Int is called a receiver here. myVar is basically an extension function literal. This means that in scope of this function keyword this will refer to the Int object, on which it has been called.

So you would assign myVar as e.g. myVar = { this } and call like 42.myVar().

  • Related