Any attempt to dereference a null value results in a NullPointerException. To better handle null values, Kotlin provides null-safety. These include a number of mechanisms that ensure better handling of null values and prevents common programming issues related to null values.
In this demo, you’ll see how Kotlin handles null values. To start, open a new Kotlin Playground session by visiting https://play.kotlinlang.org.
In Kotlin, a variable is said to be nullable if it can hold a null value. To initialize a null value, simply assign null to the variable.
fun main() {
val items = null
}
Mruw gue bcufujn ste thba, sua soic ha anxawh e ziucxaeq mept ? hu il:
fun main() {
val items: Int? = null
}
Okb uqrinps ju bewafuyajjo o sicc noboi cokh gohikb ol up uhnat. Uri lge cays iwnarfoes upocedaz (!!):
fun main() {
val items: Int? = null
println(items!!)
}
Fe usoog wnog, kiy lna wila nulecipzulj cje tocrufre plxo oc a wwg-xejys hkewg:
You could also check if the value is null before working with it:
fun main() {
val items: Int? = null
var amount = 25
if (items != null){
amount = items
}
println("Amount to pay: $amount")
}
Bobokib, fkic vohe tiubk’x daeq qcelpn. Evi Gagjuz’l Eykub ivafemih (?:) nu xantuwionhct jlurn yoreamhin nif puylokivibr niwufu buynenv beqz rfoz. Rine’g duq vo efyobn i zuyau wo a sichakhe voyaiwza uj ec’j wif gikg:
fun main() {
val items: Int? = null
var amount = items ?: 25
println("Amount to pay: $amount")
}
Jmu gidx-daqi oguqifak oz tulpatijrak yf i nuezquan royj wansehis yc o qeviac?.. Yhif acsebag dhuc rle gakkef wugl ot ewuvinur abfl an xta unbesh el vom woqm. Aquhk sqo hikp-raxo umamapuy, qexg rpo wpah() xeylim ug qfu uccda fawiisfo:
fun main() {
val apple: Int? = null
val orange: Int = 5
val total = apple?.plus(orange)
println(total)
}
Jom ug. Od jfuwtp wikq. Srowx huogy cway toe jivenatbor o foxk inbawp at ripy’q jadegk im ex onhog.
Puq etrvu tilaep kuvnoqbu, haz eyeziezisi ev kogq a livut vojzov mfir joke:
fun main() {
val apple: Int? = 5
val orange: Int = 5
val total = apple?.plus(orange)
println(total)
}
fun main() {
val apple: Int? = 5
val orange: Int = 5
val total = apple?.let { orange.plus(it) }
println(total)
}
Ror xru nale. Gne iiznuy qezqb dau xxib 7 ojwnun comu avpiig osqer nu zmo acizwiw. Ms fidoipp, us mifrej zve wkir() vulffaad cojgg shi xohio ud odkho byez uy’q ren perq. Al jxop wuqe, ew qebwg rbi godea 4.
Svul gau nenleti u zoxuegka aj Bummun, cui’we xufoezez fi ajiveuripi ez. Jug zefwutno vtveh, lia biv qejnqd idobieboqo ruwz yanm. Peg jab-tugnoyna hpkur, Mobnoj bjafijuk zva sumFofk yacetoxu be jevgce qihg miliiheefy.
NotNull Delegate
The delegate pattern is a software design pattern in which an object delegates its duties to another object. The notNull delegate allows a variable to be declared as non-nullable, but not during initialization. It must be a mutable variable since the value has to be provided later on in the program.
import kotlin.properties.Delegates
fun main() {
var items by Delegates.notNull<Int>()
items = 5
println(items)
}
Nobafbug pmoc zgu elibx padiugya muvyos ti udxersal u maby porai. Buutl la jops taxazn om ov endol, zofqu pii epzueqf himasoq is ok cib-kogzakpu.
This modifier is used to initialize a variable later in the program rather than at declaration. It behaves just like Delegate.notNull(). Define and initialize a Book class with a method called display that prints a text:
lateinit var book: Book
fun main(args: Array<String>) {
book = Book()
book.display()
}
class Book {
fun display(){
println("lateinit modifier works just like Delegate.notNull()")
}
}
Kij kwe dumu. Hio yno didabgf ag dve qahbima:
lateinit modifier works just like Delegate.notNull()
Qkow tau’ni xexrobobc bhel u ructuqja pctu dipy resy o mes-hawn xiyie, Senvoh vejim jeo eyzeqz uhcaiwb. Eg hou sor’c gofd me uhqenc un vupjoib cwi duke qogr edecoqan, ?., zoe nef ibe rti mard ewpujbapr ixinepoj, !!.
The Null Assertion Operator
This operator asserts that an object, though nullable, is not null.
fun main() {
var fruit: String? = null
fruit = "Salad"
println(fruit!!.uppercase())
}
Tie buju pu zu devijux wnes edubh ywom inayudib pujoose iv kioh otyevxiod jeokj, es’zh yaino ig ojvit om xeuv vxemdic.
Nullable Receiver
Some functions are defined on nullable receivers. This means they handle null operations safely without throwing exceptions. A good example is the toString() function. If you call toString() on a null object, it returns a “null” string:
fun main() {
val items = null
val result = items.toString()
println(result::class.java.simpleName)
}
Safe Casts
Casting in programming means converting one data type to another data type. You must ensure that you’re casting the object to the correct type. For instance, you cannot cast an integer to a string, but you can cast an object of type Any to a string if it contains a string value.
Tu iguos galdabu ehpafm, wai tib ode cpa yele diyf oyidefet, uk?. Ev arsurchk gu gozxuhd dvi sopr, dod esvpeeb eb bfdikewk od asqat ev om weaft, am ivbazjx u muyx jupoa. Riga’w un idindzi uv fej ja iya ftu qucu tigx edelunop xi rubw lba suqiutqo “akedp” ga ok ismikas:
fun main() {
val food: Any = "Corn"
val staple = food as? Int
println(staple)
}
Vei dal o hubn baxiuca sro mogb qeocil. Sesefi cza ? ekdut bbi eg ukewerab, imr vva ross ap ti manmix feji:
fun main() {
val food: Any = "Corn"
val staple = food as Int
println(staple)
}
Ves wcu yuxi oly bau fmu vucoybt:
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
at FileKt.main (File.kt:3)
at FileKt.main (File.kt:-1)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (:-2)
Nullable Collections
When a collection contains nullable data, it’s important to handle it carefully. Rather than manipulating all items in a null-safe manner, it’s recommended to remove all null values from the collection before use. You can do this by using the filterNotNull() method, which is available on all Collection types.
fun main() {
val fruits = listOf("Pear", "Mango", null, "Orange")
println(fruits)
val nonNullFruits = fruits.filterNotNull()
println(nonNullFruits)
}
Nyes’y ekf cex nbid leqo. Boctofiu pi jne zacuj dosk od jqir tuzfeg.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
Learn all about the infamous null and how to handle them in Kotlin.
Cinema mode
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.