Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does ".()" mean in Kotlin?

I've seen examples where a function has an argument given by ClassName.() This doesn't seem to be an extension function, which is ClassName.Function()

An example is Kotterknife:

private val View.viewFinder: View.(Int) -> View?     get() = { findViewById(it) } 

Which I don't quite know the function of,

and MaterialDrawerKt

fun Activity.drawer(setup: DrawerBuilderKt.() -> Unit = {}): Drawer {     val builder = DrawerBuilderKt(this)     builder.setup()     return builder.build() } 

Where the code allows you to directly call

drawer {     ... } 

rather than give it arguments surrounded by the parentheses.

Is there any documentation on this anywhere?

like image 265
Allan W Avatar asked Jun 08 '17 05:06

Allan W


People also ask

What is meaning of -> in Kotlin?

The -> is a separator. It is special symbol used to separate code with different purposes. It can be used to: Separate the parameters and body of a lambda expression val sum = { x: Int, y: Int -> x + y } Separate the parameters and return type declaration in a function type (R, T) -> R.

What does double colon mean in Kotlin?

Kotlin double colon operator The double colon operator (::) is used to create a class or a function reference.

What does Kotlin exclamation mark mean?

It's recognised by the exclamation mark at the end (e.g. String! ) and in essence just means that it's a type that Kotlin doesn't know if it's nullable or not (since Java doesn't have this built-in).

What does NULL safety mean in Kotlin?

Kotlin null safety is a procedure to eliminate the risk of null reference from the code. Kotlin compiler throws NullPointerException immediately if it found any null argument is passed without executing any other statements. Kotlin's type system is aimed to eliminate NullPointerException form the code.


1 Answers

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

Refer more here.

like image 142
LF00 Avatar answered Sep 26 '22 17:09

LF00