https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Jonathan Ellis

06/03/2022, 3:15 PM
I tried
var current: Body? = this@Body
but the compiler doesn't like that
🧵 2
j

Joffrey

06/03/2022, 3:15 PM
You should use
this@iterator
instead (the name function that has the receiver you want to refer to)
j

Jonathan Ellis

06/03/2022, 3:16 PM
oh, cool. that works but it totally doesn't match my mental model of what's going on. what should I read up on to understand better?
j

Joffrey

06/03/2022, 3:17 PM
You're thinking in terms of types / class names, you should think in terms of "who provides the
this
you're trying to access".
j

Jonathan Ellis

06/03/2022, 3:18 PM
that makes sense, thanks
j

Joffrey

06/03/2022, 3:18 PM
You can read more about it here: https://kotlinlang.org/docs/this-expressions.html
c

Chris Lee

06/03/2022, 3:19 PM
I think of it as `this`as it was at
function/label
j

Jonathan Ellis

06/03/2022, 6:08 PM
that's helpful, thanks
y

Youssef Shoaib [MOD]

06/03/2022, 7:28 PM
If you would like to access a receiver based on its type, a utility function like this works:
Copy code
fun <A> A.given(): A = this
usage:
Copy code
operator fun Body.iterator(): Iterator<Body> {
    return object : Iterator<Body> {
        var current: Body? = given<Body>()
        ...
    }
}
(This really comes in handy with Context Receivers because it allows differentiating between a
List<Int>
and a
List<String>
for instance)
2 Views