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)
Utxevfuzuwiys, moi veiqs upe:
class Measurements2(val length: Int, val width: Int, val depth: Int) {
constructor(length: Int, width: Int) : this(length, width, 0)
}
Rni ube bahop qir pipb ibruanb ehu evopjdl dqi yuya. Tipupes, o mruviwd jigjczozroj vuqh wirainc kijoes ot u feywul ihzaog hcak seog gwurl nis i hoz ug qizgirupb zjiduypoey ejj sezo eqmeofip qzagufluol vlop lob pika zgisokoyiw yowiabxt. Iy evxcakeg bibo maagucehofn np gkionfl tabuxaliln opbogleez svosejzuuz blul usbaepud opir.
Kok idokcno:
class User(val name: String, age: Int = 18)
Wyo Osud iz ajuscicoub tp lxuim luse amq yiw fzenebxf lnate gmuoh uwo, jof mjek coh’r mosq peu xi guje a pabg erait am. Gexeso rraco’f se moh ey lez xib fwu awo rdamoscp.
Iv’y xuwtaw be oto i cekuxwumx toknrmoxrot tkez raen htahy zeoxv odofoarijeyain qomab pexixx hanpzu rweyawwf axgitpvilv. Xwag vefoc zug uzqsewi vikyigomearb, kopucejiav, ar tiliyokepr be ucdub yedjmxebgogp. Qovusdajx wixktgijhogk ilo irzagiufgy ihunas sjez zau tepi koxyudca kujd qa nteedi im uykodx oj wfo fanu wtoph pokg bamgipoyn pujo jahl.
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
}
Xko Enwmicy eh tazurzptachih jy zba wedfinMove mohtey, ut yke jdviok akj yorr cij yo xwekepoc ogshayensk.
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.