is there any benefit in declaring the types of the...
# announcements
f
is there any benefit in declaring the types of the lambda parameters?
a
better readability without IDE
2
i
also type safety, I guess? remember the last expression is sent back, it can be accidentally altered (edit edit: I goofed a bit and edited in a hurry and was dumb. A better answer is: “`result` has an implicit type, derived of the types of
acc
and
i
.
acc
’s type is determined from the 0 passed to fold as the first parameter and is considered to be the expected return type of the lambda. but
i
comes from the list, which could have other types, like Long or Double or String, thus altering
result
’s type — adding an Int and a Long yields a Long, for instance. If you have the type in the arguments, it gets caught at the exact place of the issue (argument is not of the expected type), otherwise you get a return type mismatch.“)
f
thank you
although I don't get the last part
what type safety does this give me?
i
Bear with me, I’ll whip up a little example 🙂
f
thank you
i
so — OK imagine you have that very same lambda
imagine you didn’t specify the 2nd param is an Int
you could pass in eg a double
@Florian do you see what would happen?
f
but the type of the parameter isnt declared at this place right
this is the actual argument
i
Correct, it’s part of the function signature
In your example, if the list has
val items = listOf(1, 2L, 3, 4L, 5)
, for instance, the lambda will throw.
f
maybe its too late for me to understand it
I have to try again tomorrow
i
maybe I’m awful explaining 🙂
f
but anyway, thank you for your help
e
the compiler might not be able to deduce the right type without help, for example
Copy code
items.fold(null) { acc, i -> ... }
isn't possible, the type has to be given with one of
Copy code
items.fold<Int, String?>(null) { acc, i -> ... }
items.fold(null as String?) { acc, i -> ... }
items.fold(null) { acc: String?, i -> ... }
and out of these options, I'd prefer the last one
🔥 1