Could someone please tell me why I get a `Type mis...
# announcements
e
Could someone please tell me why I get a
Type mismatch
error in this code?
Copy code
private fun applyIfPossible(contacts: List<ContactEntity>): Unit {
    contacts.firstOrNull() ?.run { contact ->
        println(contact)
    }
}
s
run
is scoped such that the context object in the lambda it accepts is
this
, i.e.
T.()
rather than
(T)
, or accepts T
if you pass it a lambda with a named parameter, the compiler can’t figure out what you mean
if you get rid of
contact ->
and instead
println(this)
, it’ll work
e
You’re right, it does.
I wasn’t expecting explicitly naming a variable to break something.
c
.let{ }
would be equivalent to what you’re wanting (a named parameter passed to the lambda)
s
I think you expected something more like
let
or
also
here
c
The confusion here is that the receiver isn’t really a parameter of the lambda. It’s a variable that’s “passed to” the lambda, but the syntax and semantics of a receiver are very different from a parameter, and they are not interchangeable
e
Yes, I don’t fully grok the differences among
let
,
also
,
run
, etc. I made myself a table of whether they use `it`/`this` and what they return, but the differences seem to run deeper.
Thanks, @Shawn and @Casey Brooks. Are there any books or articles you recommend to help me wrap my head around this?
s
uhh there’s a flow chart floating around here somewhere…
e
@Shawn I don’t expect you to do research for me, just wondering if there’s some source you learned these aspects of Kotlin from that you’d recommend.
s
though you’ve probably seen it already 😅
someone also made this
though that chart is a bit inaccurate
or, rather
it doesn’t plainly state that
run
is overloaded
that’s really the trickiest part of this all tbh
e
Right, that’s what got me.
s
I don’t expect you to do research for me
no, totally, I get what you’re saying and I’m happy to dig into the archives a bit for someone making a good faith attempt to learn lol
🙏 1
💯 1
wrt the notion of there being a source for the stuff I’ve learned, honestly, I couldn’t give you a better answer than just through experience and idling on here
e
Makes sense. Thanks again for the help!
👍 1
r
The article I found most helpful to understand these was from @cedric: http://beust.com/weblog/2015/10/30/exploring-the-kotlin-standard-library/
And a prerequisite to that is really understanding functions with receivers: https://kotlinlang.org/docs/reference/lambdas.html#function-literals-with-receiver
a
Now we have a definitive guide on this topic: https://kotlinlang.org/docs/reference/scope-functions.html
💯 1
🙏 1
🎉 1
146 Views