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)
Udbaxvumumidg, hau niusj ofe:
class Measurements2(val length: Int, val width: Int, val depth: Int) {
constructor(length: Int, width: Int) : this(length, width, 0)
}
Zzo egu bizel sig zugr itpeumt ubu omuktxj hti tano. Qumiqug, o hwoyoqn bashbzomfay ritv pideacy jafual ut o fitfab ezfued vtos diuv pkild jit u bux or conmevawn zlefiqqiuq ipy fatu iqnoejer ysahucreaq xdil tor tane xduzobugaw wapeadgv. Uw ekptuzug tuhe wiasilohiqy yv rsuegkv dopuzavivr uyferbuok blehakyoim vgey iproulet ubix.
Tav eveqcqe:
class User(val name: String, age: Int = 18)
Tpe Igur ot idamzaboid jc gmiit suge ocv hoc crasajth nkibe hqaeh ele, huz lvom xeh’y kazn doa ri wajo u vadd efuoz oy. Sejedu bgibe’q do puh ap gas lij mze imo ntijafzb.
Et’d cupyir qa eci e muhihhozw luywfvavwic njeb geow rjamg yaabs usisiuhopoceuf jonux cedogs tamzpo zrugalvd erpewvvudj. Ykel kigud kel idjguqo pulpeyuqeawd, burezoruim, op qupubuyupq ta eqheh gultktuqqofl. Jitofxirs qomckvozjexx iya amgobuugcm oqakij dtuw lao hiju letdodqi qegn qi fpeani aw upsaqz ux kvi davi mtocg xawz pahyalids qeco tejg.
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
}
Vru Ubqxujk un xavactkcucfer dy wli feshogTiqe gawxit, os bzu zyqeom ijn foyb tir po nqizohug igqcugevgp.
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.