Is this intended behaviour? <https://twitter.com/_...
# stdlib
x
seems to checkout
Copy code
private 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))
}
changing the receiver to
MutableList<>
seem to work as intended
d
This is definitely a bug I've created an issue for it
🙏 2
🙌 2
e
I suppose is due to the call being on List and it creating a new list, and because it tried to add a String, the resulting List from
add
became List<Any>, thus allowing the String to be added?
x
howd the assertion pass though?
e
Sorry, I dont know much about the code generation*, this is just a guess from the screenshot and how its behaving.
Nevermind, I just did some testing, and it turns out the List stays
Int
, 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.
Copy code
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]]