Kotlin Null Safety
Null safety is Kotlin's most core language feature; at the type-system level it distinguishes "may be null" from "definitely not null".
Whenever the compiler judges a value may be null, you must handle it explicitly or the code won't compile, so many null pointer exceptions are caught at compile time.
Nullable and non-nullable types
Kotlin types are non-null by default; only by adding a question mark ? do they become nullable.
You can safely call members on non-null types, while nullable types must be checked first; the compiler won't assume they are non-null for you.
Example
fun main
(
)
{
val name
:
String
=
"Runoob"
// non-null, can never be null
var site
:
String
?
=
"www.runoob.com"
// nullable, can be assigned null
// access members directly on a non-null type, the compiler guarantees safety
println
(
name.
length
)
// nullable types require a safe call; writing site.length directly causes a compile error
println
(
site
?
.
length
)
site
=
null
println
(
site
?
.
length
)
}
Running result:
6
14
null
Note:Nullable and non-null types are the same JVM type at runtime; the difference exists only in compile-time type annotations. This also means bypassing the compiler (e.g. Java interop or reflection) can still produce null.
Safe call ?.
Safe call ?. means "call only if the receiver is not null, otherwise the whole expression returns null".
It can be chained; if any link is null, subsequent calls are skipped and the final result is null.
Example
data
class
Address
(
val city
:
String
, val zip
:
String
?
)
data
class
User
(
val name
:
String
, val address
:
Address
?
)
fun main
(
)
{
val user
=
User
(
"Runoob"
, Address
(
"Beijing"
,
null
)
)
val noAddress
=
User
(
"RUNOOB"
,
null
)
println
(
user.
address
?
.
city
)
// address is non-null, outputs the city
println
(
noAddress.
address
?
.
city
)
// address is null, outputs null
println
(
user.
address
?
.
zip
?
.
length
)
// zip is null, outputs null
}
Running result:
北京
null
null
Safe calls can also be used for function calls, such as site?.trim(), where the function is not executed when the receiver is null and null is returned directly.
Elvis operator ?:
Elvis operator ?: means "take the right-hand value when the left is null", used to provide a fallback.
Its right-hand side is evaluated lazily - only when the left is truly null - so you can safely write throw or return。
Example
// throws on null or parse failure; the right side is evaluated only when the left is null
fun parsePort
(
text
:
String
?
)
:
Int
{
return
text
?
.
toIntOrNull
(
)
?:
throw
IllegalArgumentException
(
"Invalid port: $text"
)
}
fun main
(
)
{
val nickname
:
String
?
=
null
val display
=
nickname
?:
"Guest"
println
(
display
)
println
(
parsePort
(
"8080"
)
)
println
(
runCatching
{
parsePort
(
"abc"
)
}
.
exceptionOrNull
(
)
?
.
message
)
}
Running result:
游客
8080
端口不合法:abc
The right side of Elvis can also directly be return, used for early exit from a function.
Example
fun welcome
(
name
:
String
?
)
:
String
{
// when name is null, the function returns directly and the following code won't execute
val safeName
=
name
?:
return
"Name cannot be empty"
return
"Welcome $safeName"
}
fun main
(
)
{
println
(
welcome
(
"Runoob"
)
)
println
(
welcome
(
null
)
)
}
Running result:
欢迎 Runoob
名字不能为空
Non-null assertion !!
Double exclamation mark !! is the assertion "I'm sure it's not null".
Once the actual value is null, the program immediately throws NullPointerException, so it merely defers the compile-time check to runtime.
Example
fun main
(
)
{
val value
:
String
?
=
"RUNOOB"
// can be used directly when definitely non-null; here it outputs 6
println
(
value
!!
.
length
)
val empty
:
String
?
=
null
// actually null, the assertion fails and throws NullPointerException
val result
=
runCatching
{
empty
!!
.
length
}
println
(
result.
exceptionOrNull
(
)
?
.
javaClass
?
.
name
)
}
Running result:
6
java.lang.NullPointerException
| Syntax | Behavior | Usage recommendation |
|---|---|---|
| a?.b | returns null when a is null | most common, preferred for chained access |
| a ?: b | takes b when a is null | provides a default value, early return, or exception |
| a!!.b | throws NPE when a is null | use only when logically impossible to be null |
| a as? T | returns null on conversion failure | safe conversion when the type is uncertain |
Note:Can use
?.and?:to solve a problem, don't use!!。!!should appear only where a null check has truly been done but the compiler cannot sense it.
Safe calls and let
?. can only return null or the call result; to perform operations on a non-null value, the idiom is to combine it with let。
a?.let { } meaning execute the lambda when a is non-null, with the parameter it being the smart-cast non-null value.
Example
fun main
(
)
{
val email
:
String
?
=
"runoob@www.runoob.com"
val missing
:
String
?
=
null
// executes only when non-null, it is already String rather than String?
?
.
let
{
println
(
"Send email to $it"
)
}
missing
?
.
let
{
println
(
"Send email to $it"
)
}
// equivalent if null-check form, Kotlin smart-casts automatically
if
(
!=
null
)
{
println
(
"Length: ${email.length}"
)
}
}
Running result:
发送邮件到 runoob@www.runoob.com
长度:21
Smart cast is another Kotlin capability: once a null check is done in a branch, the compiler treats the value as non-null, with no need to write !!。
Safe cast as?
Forced cast as throws when the type doesn't match ClassCastException。
Safe cast as? returns null on failure, suited to inputs of uncertain type.
Example
fun describe
(
value
:
Any
)
:
String
{
// returns null on conversion failure, no exception thrown
val text
=
value as
?
String
val number
=
value as
?
Int
return
"String=$text, Int=$number"
}
fun main
(
)
{
println
(
describe
(
"RUNOOB"
)
)
println
(
describe
(
42
)
)
println
(
describe
(
3.14
)
)
}
Running result:
String=RUNOOB, Int=null
String=null, Int=42
String=null, Int=null
Also accompanying it is is checks, which also trigger smart cast when successful.
Example
fun lengthOf
(
value
:
Any
)
:
Int
{
// after an is check, value is smart-cast to String in this branch
return
if
(
value is
String
)
value.
length
else
1
}
fun main
(
)
{
println
(
lengthOf
(
"Runoob"
)
)
println
(
lengthOf
(
100
)
)
}
Running result:
6
-1
Platform types and Java interop
When Kotlin calls a Java method without null-safety annotations, the return type becomes a platform type, written as String!。
A platform type means "the compiler doesn't know whether it may be null", so it can be assigned to both non-null and nullable types.
First look at the Java-side code.
Example
// File path: Site.java
public
class
Site
{
// without @Nullable / @NotNull annotations, Kotlin cannot tell whether the return value is nullable
public
static
String
getName
(
)
{
return
null
;
}
}
On the Kotlin side, assigning the return value to a non-null type raises no error, but a null check is triggered at runtime.
Example
fun main
(
)
{
val result
=
runCatching
{
// Site.getName() is the platform type String!, compiles fine
val name
:
String
=
Site.
getName
(
)
name.
length
}
println
(
"Exception caught: ${result.exceptionOrNull()?.javaClass?.name}"
)
println
(
"Exception message: ${result.exceptionOrNull()?.message}"
)
}
Running result:
捕获到异常:java.lang.NullPointerException
异常信息:getName(...) must not be null
Risk warning:Platform types are the loophole in the null-safety system. When handling Java return values, unless there are
@NotNullannotations or clear documentation guarantees, always treat them as nullable.
The recommended approach is to declare them explicitly nullable, then use Elvis or safe calls as fallback.
Example
fun main
(
)
{
// proactively declare as String?, handing the check back to the compiler
val name
:
String
?
=
Site.
getName
(
)
println
(
"Site name: ${name ?: "
Unnamed
"}"
)
// can also be handled by safe calls and Elvis
println
(
"Name length: ${name?.length ?: 0}"
)
}
Running result:
站点名称:未命名
名称长度:0
lateinit deferred initialization
Sometimes a property's value cannot be determined during construction, e.g. injected by a framework or assigned in onCreate , in which case you can use lateinit。
which tells the compiler "I guarantee initialization before first access"; if accessed before assignment, it throws UninitializedPropertyAccessException。
Example
class
UserService
{
// lateinit can only modify var, not primitives, and not nullable types
lateinit var siteName
:
String
fun init
(
name
:
String
)
{
siteName
=
name
}
fun printInfo
(
)
{
// use ::propertyName.isInitialized to check whether it has been initialized
if
(
::
siteName.
isInitialized
)
{
println
(
"Site: $siteName"
)
}
else
{
println
(
"Site not yet initialized"
)
}
}
}
fun main
(
)
{
val service
=
UserService
(
)
service.
printInfo
(
)
service.
init
(
"www.runoob.com"
)
service.
printInfo
(
)
}
Running result:
站点尚未初始化
站点:www.runoob.com
lateinit often compared with by lazy together; the two solve different problems.
| Comparison Item | lateinit var | by lazy |
|---|---|---|
| Applicable to variables | var | val |
| Applicable to types | non-null reference types, does not support primitives like Int | any type |
| Initialization Methods | manual assignment | computed automatically on first access |
| Thread Safety | not guaranteed | defaults to LazyThreadSafetyMode.SYNCHRONIZED |
| check whether initialized | supports ::prop.isInitialized | Not supported |
| Typical scenario | dependency injection, framework lifecycle callbacks | expensive initialization, read-only configuration |
Nullability of collections and generics
Whether the collection itself is nullable and whether its elements are nullable are two independent dimensions that can be freely combined.
List represents a non-null list of non-null elements,List represents a non-null list of nullable elements,List represents a nullable list of non-null elements.
Example
fun main
(
)
{
val names
:
List
<
String
=
listOf
(
"Runoob"
,
"RUNOOB"
)val maybeNames
:
List
<
String
?
=
nullval namesWithNull
:
List
<
String
?>
=
listOf
(
"Runoob"
,
null
,
"RUNOOB"
)
println
(names.
size
)
println
(
maybeNames
?
.
size
)
println
(
namesWithNull.
size
)
println
(
namesWithNull
[
1
]
)
// elements are String?, outputs null
// Map lookup returns a nullable type, null when the key doesn't exist
val scores
=
mapOf
(
"Runoob"
to
90
)
println
(
scores
[
"RUNOOB"
]
)
println
(
scores
[
"RUNOOB"
]
?:
0
)
// filterNotNull filters out null elements, returns List
val cleaned
:
List
<
String
=namesWithNull.
filterNotNull
(
)
println
(
cleaned
)
}
Running result:
2
null
3
null
null
0
[Runoob, RUNOOB]
Other common "return null if not found" APIs include getOrNull、firstOrNull、lastOrNull、singleOrNull, which suit the null-safety style better than exception-throwing versions.
Common questions
With null safety, will Kotlin programs never have NullPointerException again?
No. Platform types,!!、lateinit uninitialized values, reflection, and generic erasure can still produce NPE, but these are minority cases that can be actively avoided.
When should you use !!, and when should you use ?:?
when logically possibly null, use ?: to give a default value or throw a business exception; use it only when non-nullness is already guaranteed by other means but the compiler cannot infer it !!。
Can nullable types use == to compare with null?
Yes,x == null is legal and the most intuitive way to check for null.equals translation rules specifically handle the null case.
lateinit Why can't it modify primitive types?
Because primitives have default values on the JVM (e.g. Int defaults to 0), you cannot distinguish "uninitialized" from "value is 0", so only reference types can be used.