Roughly cover the materials in Chapter 6: Null Safety and Exceptions.
null
A special value means "Does not exist", "No such data", "Operation failed", "A special state", "not repersentable", or similar concept.
In many languages, null
causes crashes!
1 + null
"abc" + null
Almost all Java data types may have null
values.
In Kotlin, you need special declaration to assign null
to a variable or a value.
Nullability
null
?
mark
var x: Int? = null
null
?
mark
var x: Int = 5
Almost all types of Java are nullable.
Kotlin does not allow to assign a value of a nullable type to a variable of the corresponding non-nullable type.
readLine()
String?
kotlin-stdlib
, so you don't need to import
anything.name
can be null
: Press ctrl
+ d
to terminate the input.
name.count()
is an unsafe call!In Kotlin, there are several ways to convert nullable type to non-nullable type.
Non-null Assert: Double-bang operator !!
null
, then this operator crash the program with an "Exception"!!
when you are extremely confident that the value is not null
.!!
to fix the above sample code:
readLine()!!
name!!.count()
Use if
and != null
to assign a "default value" when readLine()
returns null
.
?:
val name = readLine() ?: ""
null
, then the result is the value on the right.null
, then the result is the value on the left.?.
: call the member function only when the value is not null
.
String?
-type variable str
str
is not null
:
str?.count()
is the number of characters in str
count()
is called.str
is null
:
str?.count()
is null
.count()
is not called.str?.count()
has type Int?
.null
?readLine()
returns null
when end-of-file reached.null
.Exception
.
readLine()!!
throws NullPointerException
when end-of-file reached.1/0
throws ArithmeticException
with message / by zero
class
to define custom data objects (including Exception
).try
/catch
statement to intercept Exception
s to prevent the crash.We can only catch certain kind of Exception
.
The exception thrown in a function myFun
try
/catch
will terminate that myFun
.myFun
will throw the exception again.try
/catch
handles the exception, then the program will not crash.main
and no try
/catch
there, then the program will crash.Nothing
is a function that always throws an exception.TODO