Ashish Suman
04/20/2023, 7:22 PMYoussef Shoaib [MOD]
04/20/2023, 7:31 PM<out T>
, and so the add call upcasts List<Boolean>
to List<Any>
and hence allows the addition. Solution here is kinda complex. Either you just use MutableList
, or you can rely on an internal compiler annotation like so (playground):
fun main() {
val list: List<Boolean> = mutableListOf(false)
list.add(1) // Compiler error: The integer literal does not conform to the expected type Boolean
println(list)
}
// NoInfer prevents the type of [item] from affecting the inferred type of T
@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
fun <T> List<T>.add(item: @kotlin.internal.NoInfer T) {
if(this is MutableList) {
add(item)
} else {
error("Not a mutable list.")
}
}
Youssef Shoaib [MOD]
04/20/2023, 7:34 PMAshish Suman
04/20/2023, 7:51 PMAshish Suman
04/20/2023, 7:58 PMYoussef Shoaib [MOD]
04/20/2023, 9:05 PMOlaf Gottschalk
04/21/2023, 11:00 AM