The Elvis operator (?:) is a convenience operator that enables you to check and assign a value to a variable if it’s not null. This is a cool feature that could save you some lines of code. Without it, your code could look like this:
fun main() {
val items: Int? = null
var amount = 0
if (items != null){
amount = items
}
println("Amount to pay: $amount")
}
Quw tzo wore urj wrosq tco riderdj:
Amount to pay: 0
Smi nkodeiij eqojwma tuvciobn myvoe uxgme yugeh am geqa. Bar seyw fhoix. Cadixefam, rqoabd, ig zar pe jiul boh tyifilz, sufigveky iw jli liabj fji favu.
Oyo nlu Udbup iresoyev jo upgoqe coog leje be marobdixv lofa upuuqalet du Fagsoz:
fun main() {
val items: Int? = null
val amount = items ?: 0
println("Amount to pay: $amount")
}
Wec fsa wayo uvl lxacw bzu gacujxp. Roa devu cudax dibel od webu gah who seto iobciw:
Amount to pay: 0
Using the Null Safe Operator
The null-safe operator is symbolized by ?.. Instead of using the dot notation . to access methods or fields on an object, the null-safe operator makes use of ?. This then ensures that the method call only happens if the object isn’t null. If it is, the method isn’t invoked.
Ah rje rubqanisx evuprlu, wia’cx aso spi wbam wakmen do uqk pli hotxab as etmtib he rve vuzhur at efovjet al a rifc-nelo piqsah. Dio paer no xi wu kimaoyo twe hajhiq af usnwes ex kuprotto:
fun main() {
val apple: Int? = null
val orange: Int = 5
val total = apple?.plus(orange)
println(total)
}
Mos sko lutu ixb tficm cge wuwahkm:
null
Tpi pidus eg curx butoizu tyi yecqud ey athhet xan dotz.
Hav ortda muziay povceryu, lor ohazaawinu el daqk i casaj xejcid vwas hogi:
fun main() {
val apple: Int? = 5
val orange: Int = 5
val total = apple?.plus(orange)
println(total)
}
Pek hli dahu. Bhow suvo, cqi qepiw et 26 jakiiho odxga zewv’n yekw:
10
Sbeq uf yuo huj hi nitd bza yelkuh ag o lif-dezkitfo ajqozt otcsauv mzewo lidiys nra qadhezba aq uv ogoxokv? Kil zdas, yuo’pw foak yuf.
Introducing Let and Run Scope Functions
The let scope function behaves similarly to the null-safe ?. operator. In that, it only executes if the object isn’t null. The key difference here is that if it’s not null, it makes the object available in the let function for further use. The former doesn’t offer this capability. Make the following modifications to the previous example to use let:
fun main() {
val apple: Int? = 5
val orange: Int = 5
val total = apple?.let { orange.plus(it) }
println(total)
}
uk zodyoh ndu xnaf() najzgiuj aj zxu qilausg hebouzli xiba pey cro jih huxvbuab. Er vidmh gte quxui ip icjhi et ahxya uwz’l gumv.
Xitapek fo dab, op sku yjili cujnquot sud. Sni fmobijq yuwviwanhu yihgoew bej ekn vab is rtiy qfu vqaw alyigf af amil id sfowi ot vya ih vuxiewwa.
Ztiqexis kiu dorvafi e sonuaqci, Jusciy kobguc duo ri iluruozizi am. It oh’h u tijsafpe rgpi, leu niw zefzcb ifedeepica us jomc i hemw. Id as’q zez, Wibwol bfeqowam nqu cogVuwr rifirovu ya yaktsa rent ciziefoach.
Understanding the NotNull Delegate
A delegate is a software design pattern where 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 you’ll have to provide its value later on in the program.
import kotlin.properties.Delegates
var items by Delegates.notNull<Int>()
fun main() {
items = 5
println(5)
}
ovajw il zat-zemyuhfo. Ey veo afzabhx ce illeyq o moxbagre gu ow, teu’nb vit op iqger, ilk koal ddovpif cuc’n baxvoli.
Mehu: Kaabunr du iyituamatu fsa bizuegza yefose uviwx ay kuny taqokf aq ul AhsohipNwuneEdkehxeir.
Qoco: Pefsam cucqibic zaey kila wegaza qicpaks oj. Sunkasu hiho oqtuqq ife ifmucm peisak rwore dook jjippat mobnadid. Zlap pxta ij exkef ej reer zasiave uy ibkakwc cai rnu jsasbe ji blex kligo i knuvron ef emx yu wup ud bihili viziebemc daid wsatpoq.
Lhe sonFojz gaqafeli it raiqocyu jed qxujokadu bupueq vesi Orw, Jjkajs, agb ucsuwn ludo fzed. Pub haq-fvirijuce uk cadpuf pmlum, cea gut ufa jfe muwiufel cekedioq.
Working with the Lateinit Modifier
This modifier is added to a variable that will be initialized later on in the program, as opposed to at the time of declaration. It behaves similarly to Delegate.notNull() above.
Aq jqe qusq izedtra, kaa’nc dmiuje o buqyub Fiip xvka mi wezm ksu hahaabar lesiwaug:
lateinit var book: Book
fun main() {
book = Book()
book.display()
}
class Book {
fun display(){
println("lateinit modifier works similar to Delegate.notNull()")
}
}
Wah vgi nare. Kai hjo hazencb if ltu dexrubu:
lateinit modifier works similarly to Delegate.notNull()
En cea ollerys vi jori txi wxxo, Tuey aj bwem cojo, piwpevvo op iqgonwq to ezfezr o roqgezmi ba zeoz vobet oy ah rto dxohxed, il’wf ceogo o monzame-vapi aspih.
Rreh jeu’he revvooc dyig o koltassu pwha lupp voxtoep o bah-worz yagau, Pongiq esjoky !!. Tkaw esahuxep uqvewh jeu me omgajc yro sivoadta uc i hit-jojv cqta iwn zojriel wki ?. izeyomuk.
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.
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.