Back to questions
JuniorTheoryCommon
What does the program print (lines separated by spaces)?
fun <T> firstOr(items: List<T>, fallback: T): T {
return if (items.isEmpty()) fallback else items[0]
}
fun main() {
println(firstOr(listOf("x", "y"), "none"))
println(firstOr(emptyList<Int>(), 0))
}x 0
- Expecting a compile error because the calls use different types:
Tbelongs to one call, so the same function works withStringand then withInt. - Expecting
Tto be written at every call: Kotlin infers it from the arguments, the same waylistOfworks out the type of its elements.
- What does
firstOr(emptyList<String>(), "none")print? - Why is
List<String>also an example of a generic type?