Kotlin , null , " ".
, Java, null .
. Java NullPointerException
(. "NPE").
Kotlin . NPE :
throw NullPointerException()
!!
( ) Kotlin , null(nullable ) , (nun-null ).
, String
null:
var a: String = "abc"
a = null //
, null , , String?
:
var b: String? = "abc"
b = null // ok
, a
, - NPE. :
val l = a.length
, b
, . :
val l = b.length // : `b` null
- /, ? .
. b
null -:
val l = if (b != null) b.length else -1
lenght
if.
:
if (b != null && b.length > 0) {
print("String of length ${b.length}")
} else {
print("Empty string")
}
: , b
(.: immutable). ,
, . val.
, , b
null .
?.
:
kotlin
b?.length
b.lenght
, , b
null. null. Int?
.
. , Bob, Employee (), ( ) Department, , Employee. , ( ), :
bob?.department?.head?.name
null , null.
- non-null let
:
val listWithNulls: List<String?> = listOf("A", null)
for (item in listWithNulls) {
item?.let { println(it) } // A null
}
nullable r
, , non-null x
:
val l: Int = if (b != null) b.length else -1
if- - ?:
:
val l = b?.length ?: -1
, -, null, - . , , . , , , , null.
throw return Kotlin, -. :
fun foo(node: Node): String? {
val parent = node.getParent() ?: return null
val name = node.getName() ?: throw IllegalArgumentException("name expected")
// ...
}
!!
NPE . b!!
non-null b
( String
), NPE:
val l = b!!.length
, NPE, .
ClassCastException
, .
, null, :
val aInt: Int? = a as? Int
nullable non-null , filterNotNull
.
val nullableList: List<Int?> = listOf(1, 2, null, 4)
val intList: List<Int> = nullableList.filterNotNull()
10.11.2021 - 12:37: - Personalias -> WHO IS WHO - - _. 10.11.2021 - 12:36: - Conscience -> . ? - _. 10.11.2021 - 12:36: , , - Upbringing, Inlightening, Education -> ... - _. 10.11.2021 - 12:35: - Ecology -> - _. 10.11.2021 - 12:34: , - War, Politics and Science -> - _. 10.11.2021 - 12:34: , - War, Politics and Science -> . - _. 10.11.2021 - 12:34: , , - Upbringing, Inlightening, Education -> , - _. 10.11.2021 - 09:18: - New Technologies -> , 5G- - _. 10.11.2021 - 09:18: - Ecology -> - _. 10.11.2021 - 09:16: - Ecology -> - _. 10.11.2021 - 09:15: , , - Upbringing, Inlightening, Education -> - _. 10.11.2021 - 09:13: , , - Upbringing, Inlightening, Education -> - _. |