https://kotlinlang.org logo
#announcements
Title
# announcements
g

gjesse

09/22/2017, 3:27 AM
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

edwardwongtl

09/22/2017, 3:29 AM
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

gjesse

09/22/2017, 3:30 AM
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

edwardwongtl

09/22/2017, 3:31 AM
In some language the + does means append, but not the case of Kotlin
k

karelpeeters

09/22/2017, 8:46 AM
It does also mean append though:
Copy code
val list = listOf("a")
println(list + "b")
prints
["a", "b"]
.
e

edwardwongtl

09/22/2017, 9:00 AM
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

karelpeeters

09/22/2017, 9:09 AM
Sure,
+
is both append and merge, and the latter has precedence because the types are more specific.
g

gjesse

09/22/2017, 12:56 PM
thanks y’all. that was surprising
4 Views