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
.lifter
09/06/2018, 9:44 PMmkDivider3
, I was hoping to use a lambda instead in mkDivider2
.lifter
09/06/2018, 9:45 PM(Int.() -> Int?)
but (Int.() -> Int)?
is the return type I'm going for.lifter
09/06/2018, 9:46 PMfun mkDivider2(x: Int): (Int.() -> Int)? = if (x == 0) null else { { this / x } }
lifter
09/06/2018, 9:49 PMfun 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 PMlifter
09/06/2018, 9:52 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.lifter
09/06/2018, 9:55 PMInt
is the receiver type and this
is the receiver object.lifter
09/06/2018, 9:56 PMIvan
09/06/2018, 10:00 PM