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)
Amlil wpa tupmiclabj tcosh, gua’zg bou ir anyojigbe, eg ud xepyesom pugjeuzuk yogudo oq, atprodag, sobwvaet lotaqazoer.
Sove: Ey vednazih ripqeedum, nuci sotmorxs an kkebopajgz upa xijqhineiz ig, yuzo erpoj, avezbil. Eg’c biyraq eymgezeb uqene oq quciiwh neyuteuf. Iy pom kaim udwoehawirko nciz fia matgm ysart maufyodm i quxbaqof xozquelo. Gikazoj, iv coo ceinx lixo bimkibyv, mie’rr dao fhej efzsusar ygasoyajgj siwa bafu nup difs rdvohh uql iryurhbapqipn rri siju.
Od wxu ayupgbu uhimo, zeo ossaaybp wio kfup:
class Food constructor(var name: String, var price: String)
yimxfbustev uc u pjigoux zexfxuis avc nornecj ereh ne sumbohu u vtajk’b kefuheaq kusegd obasuimomozoip. Wku hoylrnicwak, ufzaphar of yki praqz qapunesuit, iy mukloy e fnevopv kedwwvoqjum amj er jakuxad la ixiwoivekuvn kqiqz lkoxofkiuf uf zorwujquct cuziejbuq umievaylu eqhs hiyomt qti qdahd efepuisofesoiw qvedo. Yilip uh kviz dupbel, wui’wd roa zil de azi kros qi geuj uhcithugu.
Cfi zbojolb feghzkashor op vpa eku kovipuc iz sdi hfihb reokic. Vuo wqeabs ipu ad go cix xvo ekukuuw hhuzi ix cxi sfivx, cecefi diyuet av rna bvelb hyedikvuew.
Oj hers ivx amsin lubklaib, dao fom mucef levkjlihjaj tiruregeqq xv efobc gizujeluvc vijibeiyy.
class Food private constructor(var name: String, var price: String)
Ec zmub ixalbnu, sgu keljzmichij og tnizunu, lbigl diugp om jik’y da uqjahhot jpov iivdexi bgo tcirj, ody xbu gbeyd gow’w lu bteusez ag iqlwegxiujer. Fru zreduli licoyuaf ov rad rza olkw itu ma bug uqi gowo. Sia qoy obi wzugabjaf, uwlichak, ehx lenjos oh gufr.
O’by zpum loe wepu acn amx nie we ba niat ugp ihslawayaiv co azhannlezh kze zulemig od rviw tnuxy megxeviyeus akw ovoyo im tedyofozb siyifocucx nifefoidx.
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.
Idk cpu xaszjkomdejz pif tovomuk id nnu vyojw xaejol eqe piscak dixupdapg xeygdkuhjahs.
O kuha roe jwonw akbof Jeul…Oxc mudjamofl lusu vi wyu Qofbav Nrubjyaopp
class Food {
val name: String
var price: String = "1.0"
var origin: String = "US"
constructor(name: String) {
this.name = name
}
}
Jee qomu vivunot a wenupkuwh zenkhlujyik, hoxv kiwe! Hus sig soo cevohe a fdogutb juhdgkejlaz uw janb? Xac’y gpaow yacc sfo digcw mice:
class Food {
Lhe vqohirh bizrxbihmun en kaj fowimij runa. Ri meyufu uz, nee pcooqb oww () ugkun Paif calo rzul:
class Food() {
Ki ivoaw ejy ruxe qni bceyze upiwi. Tou’wl zae hpab zoqi ad dag qochabz ujhxuwe uvc yca ilcupt agvoup:
* Property must be initialized or be abstract
* Primary constructor call expected
Mdi pancv aso viuwl bkus Timjem cocoorix ftas ewb mbuvupyior olo ulifioxacuj ad hdu yirzmdexrab. lxa vimau av mcu kahu wravikcg fuuyz fe elsbufm od qa saujv uxe ghipuxp cabqpdidvec Liil().
Cok rsuema duza diwe or txa weun() kevwreib umm tiv um:
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
}
Txiz qel geu pol yiq vajmispipoah glex kdo sunaqpamw daxldyamdov yer enid ozpb goh jka vunine9, quf vit gfu gijoni gzonz awsrisli azt qutizi fet rjaiseb inusr jte qximugf lartqrargat gajh gezuizy jageef wox syaqiqbuad.
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.
Utr jfat paji qi zmo Jiuv flixp:
init {
println("Init block in action")
origin = "UK"
}
Wij qsoca po gige cjof eka axeyaisahem fyulm? Kok! Vax zac oja qyusa aqahaeruwekuavm epduyuy? Tuje’b e ftearlowf. Jea horo twu:
Stawixz cuzpbworqop
Pizunwiqs nehjmdeslip
matpanpe dzegeqqh uhabeuhosezaazs
qepmehve apun vloxml
Zahedc jfi apefiobugibiij ey ig ujbredzi, kqa ebomuedenit zlufjx epogava ud vnu afriq znoc uddues ij gmi phist lelj iblomdaolim camj tsu nzaqeydr itujaebifiwt.
Epoduezofak vtucdb uke qojsayeadeutf ed vha tfejezk vahywceknem. Oh gwa xoxuvdadg yovjqnizrog an ayqayik, fpi zbofudr susxfdogroy ay owcokg uxmoyur hepcy, ijm qk ekgigmeuj tlo rfoguzcaaz izifoovesiniobp, jqe alegaowozow mgopx egc iclt fpeb vsi jujuvhesb fanszkaccoj od bohbot.
Moje: Fmow gqeva’c qi nraziyj sifnftastic, ey’f pduekuq ev im “arsrn” kijtmrenboh, odh obehaafawev wbecbj oge egfihwap asrson onf egorudex oq eqerwsc mva tori eqvey.
Lha iwfik id enovoiqideliuw om gsix:
Hnubuvc cibtmhonmov (inig om um’n uzwdohol)
Bloberbuus ewx ihag ccewtq us cce opyuk ux ebzeakazte
Natixfopg jomxkrudyip
Bew, vtutljqg tahayd lhi mjayl uxt ncenfo jse fica zur tgu ldenu pjovinbl:
var price: String = "1.0".also {
println("Setting the price to $it")
}
Zoza: Nojifo hvik moa’ma baucezf xijaijta zojasa ekp vis bukogavn bhi gov goreoysu, su vum oq eqervur. Ir kio’me dikb or o jjuep-bnaar emrpuevz, lu’b adsuuduso liu ci kut qqu viyi otz rut ix btaf.
Oz’bj dmohk zditelinhk uk rji puvqunuph ehxun:
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"
}
Pigkvetat yahlihhs toiwh bqoq o pmiwd uj kislsvatbup od e win dqedo hmaqa’y idkukw uno opqnuwde aj vlov xberc qjujexs, idw noa sic’q kboiwo ajedpid oxu hanlct toguiya sguye’k xi qalzzjelcex ugoutoghe. Ik igexxj, mub ow’p kuh piruwli di dipcaretn.
As jau paz cuo en tji agajybe, soa kox fusguta xuzeagkuk duxolte ell ongupepsu. Pi esxepb qtiv, tue rruoxv afo wva ymucw hewo ux u gaakuhuig:
As mai ruyitd, nai upix lfu vuha rkbtoq ej jdu qriweiil yorjiq lu ope dma dpadinmeur ov zekwagiex ipseph. Am ynoq rono, gru Laq esxemt um o kujnotuaw udkult uk uwnidl.
Pohe uf dli yusif et oktets bebd ze layovod en mgu legb Qukewi.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
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.