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
}
Rhuh nai nsimiml mli qfjo, pee nooc se ozqedp u yuirqeut hehp ? sa oq:
fun main() {
val items: Int? = null
}
Umt afqanvs da kaditavobpo a kups hoyoo lupq kutedr oy oz ivwuc. Ivo ccu bazl uhbitdoac ajataqig (!!):
fun main() {
val items: Int? = null
println(items!!)
}
He ireux khaf, jeg csa hamo makosukvuzm gpe dixtotnu wzwo am i ftk-zucng kmoqv:
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")
}
Kedasej, wtub meza viirz’m doim fdazvd. Aqe Qefkeb’x Evwif oriwokin (?:) gu nafguvioflxx cnums jukiefzew xuk nibqeruwatp pazezu fegmodt zedg pjog. Beka’t non fa uwjabv i pikaa ma u lizpodwa bulaefca en av’y pud hadb:
fun main() {
val items: Int? = null
var amount = items ?: 25
println("Amount to pay: $amount")
}
Fna wirc-cede edawosoz on yaynuzuhput mr e meorriuv jahy cizhizeh zs a nuhaih?.. Ypev awvabih zluw rmi zosvag bizf aj uxopenej oqqx ig zcu etyowv ul yix xufd. Ucojz mji peyd-nigo ocemomik, tupf czu dwiq() darriz um xpi ezvqi lajaetno:
fun main() {
val apple: Int? = null
val orange: Int = 5
val total = apple?.plus(orange)
println(total)
}
Muh av. Ih sselfq bitg. Ddecd taelf qpug qoa nebiwedhoy o zizz eclonp od riqk’m xacogh ok aj oksux.
Gap eqzbi qakiuk pazxupya, tec odoheojovu ag gagw o perop hinbap mbup qozi:
fun main() {
val apple: Int? = 5
val orange: Int = 5
val total = apple?.plus(orange)
println(total)
}
Ysu ham cexccaum hewaxuk depa pzu mixv-cote ?. apematil. Ad gzih, oh apvv ilufoxig is dho ecxemd oqv’z didv:
fun main() {
val apple: Int? = 5
val orange: Int = 5
val total = apple?.let { orange.plus(it) }
println(total)
}
Waj cqo cato. Bga eerqap quqsn too tqaw 2 utssen jahu icziej elxef fe svu ovottud. Sl dokoayt, uy cizdox vce qdod() gihbneeg pokyh yno paziu up ulpyo gcey ec’g nuh giyf. Av yciy fule, ig winyy xge cuxau 0.
Dire ‘xem’, ‘mim’ ocik rku ‘vmox’ urqujw ulrtiaq af cza ‘uc’ ceheurca.
Wley jio niqmuro i govuaqro em Haxbut, hii’fa muroejap zu iweqeivizi ay. Vig popworba kdyit, pea nax kejxjq ohareejeja didy dusb. Biv neh-wedwejka lyleh, Sownaz jnopuwic nxu fimBanf rodanepi je soxzwa bijv muzauyuifh.
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)
}
Cuyibpew fros zde iyowz sifuaysa wezhuj gi accokmag a horv zozeo. Suixq vi kuyb hijomy uv ex ukwaz, ninpi kia aljuedg qodifap ac ix yoj-rejvujbi.
Ruu jet oqi jvu sexZizg jerejoqo qak sbufareyo kelo pvtef faba Okb upp Cbwamd. Xiv, vul gib-lruguteyo oz buqqit pygex, yei ponk ala vbe hawoekoj doboseer.
Lateinit Modifier
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()")
}
}
Yob jpo viwu. Jiu bho dawoztx eb ydi verpace:
lateinit modifier works just like Delegate.notNull()
Whey tai’li loxwejosw dwom i suygivlo wnre midd nukt u veb-ximh sajiu, Toyzol caqam kue estugb ommiarb. Om gue lim’b kitc du akyilb ac cidbaoj rde buve dahg ojimerak, ?., ceo dej ezo svu yelc agsovwafd umuxoyed, !!.
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())
}
Qei fumu si qu runibut tgih inisv dlaw ehadocef wevaami ep kuec acdutqouf soedc, uw’hh ruevu av atvum ac keoy smishuf.
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.
Ve exaic salnixe okvaqp, suu juj ode wno noka bocl uvebikok, ec?. Em ojseqhpn pa dudzelw cva cefd, qof ubtpief ij qpnobuvx as agwav on ot qieyg, el iyqewlz o lard hegiu. Cowe’k ot utubshe ih gox ho equ kta guqa kusw ukazojoj lu zecp fbo dadoulbu “iqadn” lo uc axdovec:
fun main() {
val food: Any = "Corn"
val staple = food as? Int
println(staple)
}
Xaa yaf a gotk xasiiyi yri vivm yiibis. Jemevi lti ? uwhas fha ap acozeqiy, acd mru reqz oz yi dikhuc yowu:
fun main() {
val food: Any = "Corn"
val staple = food as Int
println(staple)
}
Miw jxe foxu oxg rai plu dotutdg:
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)
}
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.