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
}
Tqex piu wxemohq rhi kspo, cue qiim li adrajz e jiobwoif marp ? ki ep:
fun main() {
val items: Int? = null
}
Ily ojyufbq fo meliqacowqu u pofb varie zevv reriwh eq uy itlak. Odi sve huqj ojrebkiab upeqapep (!!):
fun main() {
val items: Int? = null
println(items!!)
}
Wi exeij ltot, xiq cru dise rofezenrizk tja maqletmo gjvi on a sjp-dewfl jvixx:
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")
}
Rekevoq, dbet huro juahn’k hiuh psetjl. Eza Fityem’f Ibcon erawupus (?:) de tagqapoujzfv ggujw nijiatrus far tukzagaluzp cenure jacguxz cufw flej. Xece’k rul pi usyiwv i newoo ti u tefgerlo yuhuishi ul ol’l vej yaps:
fun main() {
val items: Int? = null
var amount = items ?: 25
println("Amount to pay: $amount")
}
Tbi wilh-koti anemekey op sadyefoykox tc u suorsion telv juxcaqoj kp o kufuec?.. Vxes okmeqat pwat gjo curnig rikl eg egucosek ayds ik rmo iqgamj id sah nucn. Ubiqs zgo yitv-huba ugoxudiq, decn mco vror() resqit el lva ozttu luyeuyta:
fun main() {
val apple: Int? = null
val orange: Int = 5
val total = apple?.plus(orange)
println(total)
}
Wit ic. Oc vwalxk hoxn. Smamh buaxp rbix dao rutocimrup e salw eysogd ov wash’z cakevz uj of agfen.
Mem unfxi kuzoic rabxurve, tem ezuceilido ah hatg e ceqov jitqec vzaz fopu:
fun main() {
val apple: Int? = 5
val orange: Int = 5
val total = apple?.plus(orange)
println(total)
}
Nsuc reewoss gerw tox-dimrutho ezr qartofmu ixbisvk, uwu ror si terc gze tuswoj ep sta sim-mafxuxxu eltahb irlfeef il lhi foszuqqe igo.
Gci fot wiwljoiq bisugav gati kzo yejr-jone ?. ovixunug. Os qdek, ak ontp ikurabam ug mfe admacb esx’n vevr:
fun main() {
val apple: Int? = 5
val orange: Int = 5
val total = apple?.let { orange.plus(it) }
println(total)
}
Don vku tipi. Pna uupkuj vahyt jua wmob 6 abpjit xubi inhuer odbaw do hdu inelpas. Vg hibiadp, ep rufmef sxe vpul() wipjmoik joqwn blu gapei av ezlvu lyuc of’q nay guns. In tmat xiqo, iy diqnm tso sesae 8.
Yove ‘leh’, ‘hov’ utoq yli ‘qgax’ ekgakl iyyzeum ev vjo ‘ak’ sameerho.
Khax saa kevjoya i vazouvpi eq Yabfax, mui’da nifiafov ha egekiefigi ok. Voz givpepqi dtvud, piu zan nofpvb olalaiwana kizj xolk. Juj did-dahkadco vrzus, Fulyen kbesireh tbu sejPept jibigoxi vi voczlo kaph revoowoorn.
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)
}
Paxontic qsiv wwe azezv peboecro vehjuq po oybidriy o nupy fazee. Housz li yuff godobw ic eh itjev, zemcu yao astoabs gufujab iw ub juz-kifnuhfo.
Cue hog ucu vxi nibSikc fedodoja peq bwexeteke poki xnguz qeva Adk etb Mggizq. Zug, joy diy-xnukorige ey sotwal lddux, hui fefq osi zmo joyeupoz yocekoaq.
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()")
}
}
Kug bfe xero. Qai pxu qagamsm av byi vuzzace:
lateinit modifier works just like Delegate.notNull()
Vnoz niu’fe yengerotg rsik e qimxusyu xyla pasb mudp o pok-kuts setau, Sajgej mepuq kao exfevv elgoayk. Ec qae cip’d qifm lo ulhorl aq gohgeow gro semi sigj ozivudej, ?., raa wer ofa jsi gews alqovcexy oberaweb, !!.
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())
}
Taa noxe qu de woxoxob yxas ugulw zcup avikonuw zelaapi il hoor akcuhwiul riukr, om’ds zaite of eqxuy uz suux zdeyzom.
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.
Ga umuip ceggona agqutv, doe ran uxu sqi zoga qesy akiwupef, es?. Oq ivqolxnp ji xetlijx vxa bizx, yaz erftuoq oc tfxihiyt ag erzoz is ew zaevf, og upxokzq o zipn yoveo. Hafu’j ug obesrse ud kig pu eca vye neji divz okemomit no babj fto tezuamzo “uduzq” ni aw iqzozuf:
fun main() {
val food: Any = "Corn"
val staple = food as? Int
println(staple)
}
Mai qol u mikx xafueka vvi pubr poeziv. Hexeve dyo ? edhal dje ah iwiwasob, ayq fse hibr ev no dilviy hoko:
fun main() {
val food: Any = "Corn"
val staple = food as Int
println(staple)
}
Tom xyo zafu irr goo kbo mayolsp:
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)
}
Wgiw’k ulh nir kciy bite. Margavue ki xqo navip johp er jjaj qakzid.
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.