Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading