why in Kotlin, Stack<Int> can push(null) but ArrayList<Int> cannot add(null)?

Viewed 91
fun main() {
    val stack = java.util.Stack<Int>();
    stack.push(null);
    val arr = java.util.ArrayList<Int>();
    arr.add(null);
}

IDEA underlines the null in the 5th line with a red wavy line and warns that Null can not be a value of a non-null type Int. But It ignore the null in the 3rd line.

And after deleting the fifth line, the program can run normally.

why in Kotlin, Stack can push(null) but ArrayList cannot add(null)?

Thanks.

1 Answers

ArrayList is one of a few Java collections that are treated specially by the Kotlin compiler, which has been set up to recognize proper nullability when working with it. You can see all of them here. I believe they've manually configured to compiler for the specific methods of these Java classes.

Since Stack has not been set up in this way, nullability is not enforced on its methods, as is typical with most Java classes in Kotlin.

Related