The it notation

We glanced at the notion of it briefly in previous chapters, but for this chapter, we need to understand it a bit more (pun intended).

Kotlin is all about brevity. First, if our lambda doesn't have an argument, we don't need to specify anything:

val noParameters = { 1 } // () -> Int implicitly

But what if we have a function that takes another function as an argument (and doesn't do anything with it for simplicity)? See the following code:

fun oneParameter(block: (Int)->Long){ }

We can specify both the argument name and type explicitly, and wrap them in brackets, like any other function invocation:

val oneParameterVeryVeryExplicit = oneParameter( {x: Int -> x.toLong() })

But since the lambda is the last parameter (and the only one, in this case), we can omit the brackets:

val oneParameterVeryExplicit = oneParameter {x: Int -> x.toLong() }

And since the compiler can infer the type of parameter, we can omit it too:

val oneParameterExplicit = oneParameter {x -> x.toLong() }

And since x is the only parameter, we can use the implicit name for it, which is it:

val oneParameterImplicit = oneParameter { it.toLong() }

We'll use the shortest notation in most of the following examples.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.190.175