I will assume that you come from Java, you already looked at some explanations somewhere else and did not fully understand them. Therefore, I will not try to give you a comprehensive explanation (which you can find elsewhere) but instead I will try to make clear the core idea of null pointer safety.
There are two points that, if you understand them, should make it clear enough. First, there is the idea of having two separate types to represent what you would model as a single type in Java: nullable ones and not nullable ones. To give you an example, while in Java you put a string in a String
object, without caring if the string can be null or not, in Kotlin you have two types: String?
and String
. The first accepts null values (like the Java equivalent) but the second does not. So you can have null values in types with a ?
(like String?
or Int?
) but there are a lot of restrictions on what you can do with those: basically you are restricted to the things you can do with a null, because, after all, the variable could be holding a null value. So no calling of method on it, for instance. So, while in Java you could call a method on it and have a NullPointerException
sometimes, in Kotlin you cannot call any methods. And this is not because of some silent behavior of Kotlin, it’s much simpler than that: the compiler won’t let you. Try and you will see that the program does not compile. If the variable was of type String
instead of String?
then Kotlin would allow you to call methods from it.
因此,基本上没有空指针异常,因为您永远不能对可能为空的对象变量调用方法.
But then, sometimes the variable is not null: so how could you call the method on the variable in those cases where the variable is not null? Again, the answer is simple: you have to check it. I mean, you have to use an if
instruction (explicitly or implicitly) that will check if the variable is null or not. Something like “if (myVariable != null) {call method on variable}
”. So, as you can see, the Kotlin compiler is clever enough to see that you used an if
instruction that guarantees that the variable is not null, so it will let you call methods on the variable in the block between {
and }
. In other words, if your variable is of type String?
but you are inside an if
block where you checked that the variable is not null, Kotlin will treat it like a variable of type String
instead of String?
When you speak about
some part the code which silently won't be executed
我猜你在想一些操作符,里面有一个隐式的if
,比如?.
操作符.如果你写信
myVariable?.call()
it means roughly
if (myVariable != null) { myVariable.call()}
个
因此,事实上,如果变量为null,它将silent地"失败".但是如果你使用同样的if
,这和Java没有什么不同.换句话说,如果变量为null,则不会发生任何事情,因为您显式地将其编码为那样的行为.