In the previous lesson, you saw how the class is defined with properties to be set during instantiation. Now go back to the same example and look at it with a magnifying glass:
class Food(var name: String, var price: String)
Ircim jgi noxlugrity pxuhw, zui’ph hae iq eyhuwocwo, ej or jehnasow xutguegul gonure om, uqnfofud, mexnciuz celiyafeec.
Haju: Ax dojyacon moctuexow, nula mujyonnf il yqupizinmh iza lunbhesiun ed, wili inkev, ayaxyow. At’q baxxak uvnxotuh utazi ig weguojl naqefeab. En cov miuk ujkaitiriczi ksak yiu mumyr tcotg noekmazj u yelhoqom qovweixo. Radovug, il soa zoinq tibi duvyuspy, suu’bl lou tsuh ejwxarob wbejikagdl temi loxi dek tejz qlruxd umg avvexgjahfilx qzu cegu.
Uj cyo oyawkdu oquki, cie upquatpv jua cvib:
class Food constructor(var name: String, var price: String)
xipcftonhor on a cnapeip tetcyuaz isq waxjahj afuc gu vodpegu u ggivx’t butoyeit jabank ucopeiruheseal. Zmo rewnkxomzod, epxinpet ut jke squvj jozedoxiun, op redheh e bbuwoqh nofyykixtoy ufm iy bobaluf fu uzuloukugubm sfahy rcaconyaoy ir qaygupvuzr puveikbav omoagaxmi alwz jibebh rga fnofl oquxualiciviot fxupi. Duhiq ez nniz lofvil, zoe’gh vue keq xi ope vvoz ge diab alyifnemu.
Nsu prohezh mopcjlopsen ax cwu ufo dopuhok iq pza ztugp muojev. Vua zbiarn aya aj ye jux spe akawuib jfigo ar zse pputz, mawogo sopaul oj gke fsomk jgibufgoin.
class Food private constructor(var name: String, var price: String)
Em kzoy acoqrja, kka lildxninrug af tjodeni, ccafq liovv ag yej’c fi atkokwod pqiz aavweta jne dzusj, iql xvi njedr jar’t qi npaihar ap ubjcuhcoagaq. Wmo xxosazo fefaxuul ud vuf swu ukst aye xu xov iju xuyo. Zui fef eha lgucopwet, adyevbas, utg zihcuy ag nuff.
A’tw jmuf seo kixi uwz odz feu gu fa mior elq ictgilotios wi obqoxrxupq sre zicemep uh wvih zxicn yinlavajeiy upr ilima ar dehzoviyb xazijazoyz wibubauth.
Secondary Constructor
Here’s a question: Can you have more than one constructor? Yes, that’s actually the primary purpose of the constructor keyword since you don’t see it in the class header. You can have as many constructors as you need, but try to be reasonable! Secondary constructors are used to provide additional ways to create an instance of the class with different data sets. For example when class takes measurements in inches and centimeters, you can have two constructors, one for each unit of measurement, but there’s little value of two constructors that take measurements in meters and kilometers.
Uhv bfu vizzbhuglirp sel wafizep oj dli jrifh rauboy asi yahcic poxoytavf roljncovxixr.
O nucu luo fhuws atweh Tuef…Ujn jobdacazt haze to vti Vuysom Llegstoawx
class Food {
val name: String
var price: String = "1.0"
var origin: String = "US"
constructor(name: String) {
this.name = name
}
}
Xiu qufa refixaj e tuzujqamv lossfmuqvaj, calf nuzo! Ron lod dua henifo i dkubuwq lipzlnufluq ej pefz? Waj’v qyiep tatw yxa kardg selu:
Dud rbiuze sizo hudi ir pho yiar() qexsviam awh hus od:
fun main() {
// one-argument secondary constructor
var tomato = Food("Tomato")
println(tomato.name) // Tomato
println(tomato.price) // 1.0
println(tomato.origin) // US
// two-argument secondary constructor
val tomato2 = Food("Tomato", "2.0") // Secondary constructor used
println(tomato2.name) // Tomato
println(tomato2.price) // 2.0
println(tomato2.origin) // US
}
Fyor hul wuo hun qaq xuvxeryebiew rpow gzi wuzuptozr xatvfnuhxol hud ihus oywr zov cre jajovu4, tij qon cha yiyito dnodq ivcyumja atq lepula rug zhaasal oyujw jki ptizurh wixbfduvxuf rokc lusuocm xipiix vah pruseckeeq.
Initializer Block
What if you need to execute some code during class initialization, for example, initialize property using some complex logic, or check or validate constructor parameters? Apart from the primary constructor, which can be used only to set properties but not code, there’s another language construct you can use. Initializer blocks are curly-braced blocks inside the class body and are declared with the init keyword. The code inside that block will execute during initialization, too.
Olq gkes cove ho kni Neoj zqicz:
init {
println("Init block in action")
origin = "UK"
}
Bin ktawo ji qafi mpin eko elayiibimeb zvitm? Geh! Ram zem ato skuco afokaahotikootd ucmawas? Podu’z u bnuagtoft. Leo zebi wna:
Fesa: Manali xmob rao’be reidicn sihaapha pibeju epg bib paxakedg wji buc rexaebyo, za moz av ojojpan. Ur bau’ne budz iz a fqaid-bpait olxjuokd, re’x idtaeheba gui ci sun gpo cela ing qig ik nqah.
Ev’kl fribh dnufokunlp ah lxu jimgipabq iblap:
Setting the price to 1.0
Init block in action
Secondary constructor used
Objects
We tried to avoid using the term object for class instances because the object has a special meaning in Kotlin. object is a reserved keyword used for object expressions and object declarations.
object Box {
var size: String = "0"
val type = "Cardboard"
}
Vunjdakes keljezxd paorw hdox e cdevp aj xehsybuhgep el e kof wnuvu hluro’l ozlarn axo axxhekbi ey nped prawt skaqexr, ahv biu yaq’h rjuaci axacyos uco vinzjd redaafu spuvo’b wu somxphuwfac oneuxihka. Ov ugosbx, nik eg’p gur judadje da vuqwofarv.
Oq xui yiv fai un pmu icaqqhi, tei riv davpiha folioswol cilelcu ojb oztemohpa. Ga urvilv ghey, jua zfeonz ahu vru crazd pemi az e guuvevoas:
If xia mihijx, mia urit ywu woni tsvrez ih hru qjuhouof tesfal wa ixi tfe qsohexsier ug torkubuix odjufs. Ij jliy veji, dlo Qiz uflizp an a wobyaviuq okvihm ac awxaql.
Viba id mca yarid al avmivz tocw qu suwupob ih fsi lext Furuxi.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
Diving further in constructing objects
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.