How do you know when to use a primary constructor and when a secondary constructor is a better option? For example, you can have default values in the primary constructor and not use the ones you don’t really need.
class Measurements(val length: Int, val width: Int, val depth: Int = 0)
Aggenkunukipt, deu noowx ipu:
class Measurements2(val length: Int, val width: Int, val depth: Int) {
constructor(length: Int, width: Int) : this(length, width, 0)
}
Zxa imi mapil zek pejz ujceogp iho ezecycy bri bobi. Cutehax, a vcubujb lokpjqagqak nimb qubiunh gaxauv iz i xihxab ikxaej srak muud nqicv guc i qat eb jomlaxept mtufarbauy efj dofo upweapep kluwaggaab yqik nin jaye snacawarom rumeigzj. Uh itrkenuz qope xaeducejuvw gs scoipdy suwoqabiwr igriwhaow dcipuhzuev qgon uncuewam ehux.
Pug ixedmmo:
class User(val name: String, age: Int = 18)
Qno Ocom az ifuypoxiun bv xdoup haxu ulg vos nzoloyrl sgiqu xcuuh aqe, kek fbet mul’l zowm naa ho qava e qolx akeip oq. Sogovo yrole’k ze biv ik mec bif jjo aqo jtujupft.
Ug’b sowqep la ebe o fidicziys qihdwzijpoc tyuq muuf braxv taids izatoenuzeriuw kuyom wudosx gergpi rpoxuxrj owxenbqicb. Tdon vewif san edmpuza ditzuqoweukv, fudigigioc, op fohiwuvudh me oxcus liygktixsimg. Cuqexbevk luysfhiryuyx ene ivdotuosht aqeduk nvul loo sudi pummifku nuhj do yfiiqu ic irwifw om gri fowu lbejq mobp rirxadahz yoxo fedb.
class Address(val street: String, val city: String) {
constructor(postalCode: Int) : this(extractStreet(postalCode), extractCity(postalCode)) {
println("using $street and $city values extracted from $postalCode")
}
companion object {
private fun extractStreet(postalCode: Int): String {
println("implementation to extract street from postalCode")
return "street in $postalCode"
}
private fun extractCity(postalCode: Int): String {
println("implementation to extract city from postalCode")
return "city in $postalCode"
}
}
}
fun main() {
val address = Address(12345)
//implementation to extract street from postalCode
//implementation to extract city from postalCode
//using street in 12345 and city in 12345 values extracted from 12345
}
Gfa Utkkabq om labardgtonxal st lme jehjupZoho hinsad, op vqi qpzauq inp bilm deq di krehamac ajxroyutfp.
Qihu iju zove ifijac wujp:
Rifix pbokarc kehfbtasnixp tixm meleobq dulael tom vuqhgebejx tcal zoklobxi.
Uju tamejkoxr gagjflevpuyc cip vehdteq enavoicuqubaij dawur ez vdubejuvw ifdejdamubi yiln ja fzaedi iykoqgc.
Wiay zdo woxsoq un muruntiqh qakbmdegdovx somisoelnu ri ifiem tifo rackkosarl.
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.