i feel like this should work, but i get “Type infe...
# announcements
g
i feel like this should work, but i get “Type inference failed - required
List<List<String>>
, found
List<Any>
Copy code
kotlin
    val hmm: List<List<String>> = listOf(
            listOf("a"),
            listOf("b")
    )
    val hmm2: List<List<String>> = hmm + listOf("c")
e
hmm
is of type
List<List<String>>
while
listOf("c")
is
List<String>
, so the end result become
List<Any>
Instead you should do
val hmm2: List<List<String>> = hmm + listOf(listOf("c"))
g
duh yeah .. just figured it out
for some reason was thinking it was + the element value
but it’s concatenating 2 lists
not appending an element
e
In some language the + does means append, but not the case of Kotlin
k
It does also mean append though:
Copy code
val list = listOf("a")
println(list + "b")
prints
["a", "b"]
.
e
Well, when I take a look in the plus operator, it will auto flatten the
listOf("c")
, since it is a collection
Copy code
public operator fun <T> Collection<T>.plus(elements: Iterable<T>): List<T> {
    if (elements is Collection) {
        val result = ArrayList<T>(this.size + elements.size)
        result.addAll(this)
        result.addAll(elements)
        return result
    } else {
        val result = ArrayList<T>(this)
        result.addAll(elements)
        return result
    }
}
k
Sure,
+
is both append and merge, and the latter has precedence because the types are more specific.
g
thanks y’all. that was surprising