xxfast
09/06/2022, 11:51 PMxxfast
09/06/2022, 11:52 PMprivate fun <T> List<T>.add(element: T){
if(this is MutableList<T>) {
this.add(element)
}
}
@Test
fun test() {
val list: List<Int> = mutableListOf(1, 2)
list.add("NaN")
list.add(null)
assertEquals(list, listOf(1, 2, "NaN", null))
}
xxfast
09/06/2022, 11:56 PMMutableList<>
seem to work as intendeddmitriy.novozhilov
09/07/2022, 8:02 AMEric Ou
09/12/2022, 9:28 AMadd
became List<Any>, thus allowing the String to be added?xxfast
09/12/2022, 9:30 AMEric Ou
09/12/2022, 9:30 AMEric Ou
09/12/2022, 9:40 AMInt
, it's just somehow a method which only accepts Int
can take Strings and nullable values. Which I think is the real problem here.
For a List<Int>
, List<T>.add(element: T
, the method should only accept Int
and not what it seems to practically accept, Any?
, I think this is a compiler issue for not checking it properly.
import java.awt.Color
fun <T> List<T>.add1(element: T) {
if (this is MutableList<T>) { // no error
this.add(element)
}
}
val list: List<Int> = mutableListOf(1, 2)
list.add1("NaN")
list.add1(null)
list.add1(Color.BLACK)
This code should not properly compile and run, but currently does, and is somehow List<Int>, even though the list evaluates to [1, 2, NaN, null, java.awt.Color[r=0,g=0,b=0]]