Hi I have a quick question, in documentation it sa...
# react
d
Hi I have a quick question, in documentation it says that in a list all of the elements have to be of the same type. That being said, why doesn't a listOf(1, 10.0, "ten") give an error ?
b
Because the inferred type is Any and all the items are of the same type (Any)
d
how can it be both same type and any
sorry I'm fairly new
b
You can try explicitly specifying the type to see how it breaks. The bellow won't compile: listOf<Int>(1, 10.0, "then")
d
right I realize that
so a list doesn't have to be of unique elements if a type isn't specified
b
how can it be both same type and any
They are all inferred as type Any, which is the root type in Kotlin. Just like Object is the super type of all other types in Java.
Son in your example, kotlin type inferrence finds the least common denominator for all argument types (which is Any) and returns List<Any>
Now if you drop the string from your arguments and have listOf(1, 10.0), the closest common type of the two arguments becomes Number and you get List<Number> returned
d
got it I think
but I think it's wrong for the documentation to state it has to be of the same type
b
In all the cases above, you get a list which has all of its elements be the same type (specified or inferred in generic argument)
but I think it's wrong for the documentation to state it has to be of the same type
Why, that's exactly right
d
listOf("a", 100, 10.0) will also not break
b
Nor it should since you leave the generic arg for type inferrence
d
but it's three different types or two since 100 and 10.0 are of the parent Number
b
No, it's three same types - Any
Any is a type
d
ah
b
val x: Any
d
so what would be a type that would be incorrect to combine
if it says it has to be of the same type
b
None if you don't specify the type yourself. All kotlin types inherit from Any
d
got it
Thanks
b
You're welcome
d
What's [G] in your name?
b
Google
d
nice
Can we connect on LinkedIn?
b
Don't use it when I'm not looking for work tbh
d
ok
b
You can ping me here though if you have further questions
d
got it thanks