Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

oop

kotlin

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.

like image 456
dafttttttt Avatar asked Jun 18 '26 19:06

dafttttttt


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.

like image 76
Tenfour04 Avatar answered Jun 20 '26 10:06

Tenfour04