Can someone please explain why `mkDivider1` compil...
# announcements
l
Can someone please explain why
mkDivider1
compiles but
mkDivider2
doesn't? (
'this' is not defined in this context
)
Copy code
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:
Copy code
fun mkDivider3(x: Int) = if (x == 0) null else fun Int.(): Int { return this / x }
i
Shouldn’t your second example be like this?
fun mkDivider2(x: Int): (Int.() -> Int?) = {if (x == 0) {null} else { this / x }}
l
Wait a sec... woah.
i
If I understood your intent correctly, you need another pair of curly braces to make it a lambda and a question mark after Int (lambda’s output) to be able to return null from this lambda
l
Yeah what I'm trying to do with
mkDivider2
is exactly what I managed to do with
mkDivider3
.
But while I'm using an anonymous function in
mkDivider3
, I was hoping to use a lambda instead in
mkDivider2
.
So actually not
(Int.() -> Int?)
but
(Int.() -> Int)?
is the return type I'm going for.
But you gave me an interesting idea:
Copy code
fun mkDivider2(x: Int): (Int.() -> Int)? = if (x == 0) null else { { this / x } }
WOW, yeah that seems to do what I intended:
Copy code
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.
i
Well that’s great! So you see, the problem with your first attempt was that you weren’t returning a lambda from if expression, but a result of divide opeation.
l
Right!
Thanks!
i
You’re welcome
l
I think I'd be correct to say that this particular lambda (
{ 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.
Please correct me if I'm wrong. 🙂
i
Well, as long as the compiler agrees with you, you’re good 🙂