A reference must be explicitly
marked as nullable when null value is possible.
Return null if str does not hold an integer:
fun parseInt(str: String): Int?
{
// ...
}
Use a function returning nullable
value:
fun
printProduct(arg1: String, arg2: String)
{
val x = parseInt(arg1)
val y = parseInt(arg2)
// Using `x * y` yields error because they
may hold nulls.
if (x != null && y != null) {
// x and y are automatically cast to
non-nullable after null check
println(x * y)
}
else {
println("either '$arg1' or '$arg2'
is not a number")
}
}
if
(x == null) {
println("Wrong number format in arg1:
'$arg1'")
return
}
if
(y == null) {
println("Wrong number format in arg2:
'$arg2'")
return
}
//
x and y are automatically cast to non-nullable after null check
println(x
* y)
Null
Safety : Using type checks and automatic casts
The is operator checks if an
expression is an instance of a type. If an immutable local variable or property
is checked for a specific type, there's no need to cast it explicitly:
fun
getStringLength(obj: Any): Int?
{
if (obj is String) {
// `obj` is automatically cast to
`String` in this branch
return obj.length
}
// `obj` is still of type `Any` outside of
the type-checked branch
return null
}
or
fun
getStringLength(obj: Any): Int?
{
if (obj !is String) return null
// `obj` is automatically cast to `String`
in this branch
return obj.length
}
or even
fun
getStringLength(obj: Any): Int?
{
// `obj` is automatically cast to `String`
on the right-hand side of `&&`
if (obj is String && obj.length
> 0) {
return obj.length
}
return null
}
Hello Reader
You can comment if any confusion in syntax or if need more explanation we'll reply you ASAP.
Thank you Safe & Happy Coding. :)
No comments:
Post a Comment