lifter
09/06/2018, 9:29 PMmkDivider1
compiles but mkDivider2
doesn't? ('this' is not defined in this context
)
fun mkDivider1(x: Int): (Int.() -> Int) = { this / x }
fun mkDivider2(x: Int): (Int.() -> Int)? = if (x == 0) null else { this / x }
By the way, this one does compile:
fun mkDivider3(x: Int) = if (x == 0) null else fun Int.(): Int { return this / x }
Ivan
09/06/2018, 9:37 PMfun mkDivider2(x: Int): (Int.() -> Int?) = {if (x == 0) {null} else { this / x }}
lifter
09/06/2018, 9:41 PMIvan
09/06/2018, 9:42 PMlifter
09/06/2018, 9:43 PMmkDivider2
is exactly what I managed to do with mkDivider3
.mkDivider3
, I was hoping to use a lambda instead in mkDivider2
.(Int.() -> Int?)
but (Int.() -> Int)?
is the return type I'm going for.fun mkDivider2(x: Int): (Int.() -> Int)? = if (x == 0) null else { { this / x } }
fun mkDivider2(x: Int): (Int.() -> Int)? = if (x == 0) null else { { this / x } }
val f: (Int.() -> Int)? = mkDivider2(0)
println(f?.invoke(20))
It prints "null" as I hoped.Ivan
09/06/2018, 9:51 PMlifter
09/06/2018, 9:51 PMIvan
09/06/2018, 9:53 PMlifter
09/06/2018, 9:55 PM{ this / x }
) is an example of a "lambda with a receiver" because altho it's a lambda it satisfies the type (Int.() -> Int)?
- an extension function type - and I can use this
inside this particular lambda.Int
is the receiver type and this
is the receiver object.Ivan
09/06/2018, 10:00 PM