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?
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.
Kotlin double colon operator The double colon operator (::) is used to create a class or a function reference.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With