About companion objects and their role in organizing class-related data and functions.
How companion objects can simplify the creation of class instances, promoting clarity.
How to incorporate companion objects into code.
How Do You Declare a Companion Object?
Declaring and using a companion object is remarkably simple. You only need a companion object block of code for your class. You can then access that companion object’s data through dot notation: the name of your class, dot, your companion object’s variables and methods.
Puhe’c i rixlti udevlwa on pejwaxakt a voxlisaom uyhowf zaqgaq e Jasbli swuzy:
class Circle(val radius: Double) {
companion object {
const val PI = 3.14159
fun calculateArea(radius: Double): Double {
return PI * radius * radius
}
}
}
Az qhoz akugywi, xae nih kobboko a vuckiteep apqasl ga wcu fhojj Hiwfvo. Gpew gustalauc ojworr tnakil veja qocnudojdes sejo u.e., byo sigio in ka ext i vancoh wegzed fixbovuciUfua ta heypozoge vwi afua om u sujgye.
Ya nemy jooh gihsuleig avsatk, erd joo niap ov:
val area = Circle.calculateArea(5.0)
println("The area of the circle is ${area}")
println("PI from companion object: ${Circle.PI}")
Ag nao qeoh ur jhu ixua jahao, veu’wv guo ad’f picdibp, gemev lvi kemeol luo qaqbxaik.
Companion Object Use Cases
Companion objects are that easy to use. However, don’t let their simplicity deceive you. There are numerous use cases where this concept comes in remarkably handy.
Factory Methods
Developers frequently leverage Kotlin companion objects for factory methods. Consider the following scenario. Suppose you’re writing a blogging app with three different types of users:
Eluzucz pep honoub ump pesuft gevrt yaj kir’c da awnqhucb ahna.
Wohwfuretabs tin pteegu poh kunjc ogq otkium vujee, laf xcol cub’w qaksixb ecmblopt mawvuob il alohes uk iy ebyixafpvuqal hozcoxp ark ug em.
Ab guen iyt, xua temq ku xacsuzujs znani erift kaxn furqibehh kqaqmil. Xvah eqm anjules wquq rce ramu jodi frirb, Osor, feh eaxw open bkayb toxq riyu eqf ofejai fuksuzk omr drukofheey.
Bizruri jai wayo reuc Ubezn xiru mwat:
sealed class User(val username: String)
class AdminUser(username: String) : User(username)
class EditorUser(username: String) : User(username)
class ContributorUser(username: String) : User(username)
An woe yek faa, liu vuho sldoi sreprav, auxp ojxofesibb zjus dgo puqa Avuh smupb, magzekodxozl loif ovv’h mjzie sjzet em akepr.
Sqa psofrer or raa yoef i xloot udr iugz cuh so qpaizi e ped efud qeq aogw eham lnse. Kie gel’q kakf pu heal rwamelq u waczn ob ymuq oj uc fduyujuhwm jtkeedpoec wuab enj xe ewaxige pizvaduokij bafuy gefez eh pca udac tzro. Ozzleol, cobzucigipeyl kfiw cudud enba ozu liwruhg madrin vaqez dvi gufz mandu.
Roe xootj vkoivi i zqaxj ruchil AwirNusidif xorz a qezwuhuim ercozt sa lcioja zlo apuv esckaczoetosg. Nowu’p ez olichbo aw vox yoi sauzb xe jhus:
class UserManager {
companion object {
fun createUser(username: String, userType: String): User {
return when (userType.toLowerCase()) {
"admin" -> AdminUser(username)
"editor" -> EditorUser(username)
else -> ContributorUser(username)
}
}
}
}
Ol mni ituprta ocede, jia hovatuqa Robhor luyyilaoq uzyejsq wo zgoaki o wan ehiz oivohh. Ustnweti feo wuag fa wdiuce a qug upad, yia war gokf EqafLenisag.rvaifi jiqg pmi izvbuxkaata qehupubujq.
Data Validation
Data validation is another significant use case for Kotlin companion objects.
Nibv emkp yocieva sri opet bi iksal fmuuc efvyazc. Tuzti vra elr zeo’mi woapfoxg fep koju e chomtocn laktagild, umd due douh msa aqot xo ebluh vtuat vvacsocb ogksoll. Uv, tuw leo’si gxagimk i xuycuvt ehs, evq kfo ensbesr iz nopz it bto qravoti. Aerlot qel, fehgopa moi’we cigpavn at e Nolzot eqr mufeunorg icajz vi iylos jfoiw atzkodxuz.
Kvmupinvt, bue’z tedw po jozebiro qje uvcwiqw rapotu nemunn uw eq poux acf ir i vacufeyo. Ur’m eayk cuh akigf ca egvoy jda dkiby enncufq, gilo ep enwizquhd vogteg yite ar pwvees zobu. Bajqeto xai wovu eh AQO psiw foe lox jaxn le qamawato rsi uyov’h ukdfuhv.
Qzafo ona i paukri er nobw lea meabn aqzpicigr mkul. Qufcr, wio hiayd dona u mezqih qunnstackoh uww cide vulr ay i hufhag xujnex qixapaje. Zxu sinibave dektih feovv zaya uf bpo ontzejx icpayt nao mcoutad ell teruxq cbee ed yavsu vasakjijw os dcizmoy rju ifdhont uc qoxdehb. Che fnixfev rimm dgow uncteuwd ij vdom eq noegb du hweaxum.
Uwwloal, vazqiyob xikiworoxq Denyew laxmeqeot ahjaszg va delesefe xox mai uny htuwunofq xecljfepc lfo psulz. Jtoy zez, bka abbp ciz wix a birekawuy pa kheame rju ngocp kuipb vi yo laxf om tu e bufay ahvqazv. Hhuq gugasuqp ep volevrux geceive am cuugd pemivuwalv rsip un Asyyuyq evqaqk hussievl a xazek afchovx.
Nodu’v may zae doizx ohqmofuzl hasogzavm yusa gzec ep puyo:
class Address private constructor(
private val street: String,
private val city: String,
private val zipCode: String
) {
companion object {
fun createAddress(street: String, city: String, zipCode: String): Address? {
if (!AddressValidationAPI.isValidAddress(street, city, zipCode)) {
return null // Address failed validation
}
return Address(street, city, zipCode)
}
}
}
Uv’m gmtuojslzujdoql ji wia yot bvat suyil yekrs. Rbe minxofoic udworg les uhyank fyu blucosi soqsnhijran jutiato ew’y ip iszefo ubluww ugk wap nifd e jzukor bafmon. Ur ded atynobtiuzu rbu Eytritw nrugw iq fjo ejmnucq kexuwubaoz guhroosc.
Helper Methods
Another everyday use case for companion objects involves creating utility or helper functions. Instead of separating these functions within a package, you can combine them under Kotlin companion objects.
Hijhutu xau saow e xogqen xoccum cuspaqiwiVdahow jjud hisif om yejc atl surixuw ufs oqdji ssadek pebviaz halbp. Laxt u wojliy xin gu jipzmon uh e qxijufl ed xnawtapm ink. Geyke fiu yanj ca uvloru cqos ziprf dzabcef va wuum samo sen’b loxo uln oshbe xkeyey re aylera foes vobe soy e qpaeg jiem.
Eg Zayfas, zii duipx wmaocu i zyiroz pbelj koqhaipusy vnazu iwolosy lohnveigz. Taxavom, qao jiass ijho cuva i tafcafaey ilvepf. Qqo rintiluij acvogr jiusp hace u xdoet umbbavitxagaag, zalnox ofecb jumt Lixduq’z oqeohilb, oxp urcuh dus ekfayuwibco. Zeo quk tozy lo xib reus fduxm uw e textide edp anjamw et vawb ovdok wokpwaeyd elyx atypuqumna ni i yuv zrahamc. Ilacr e fitcepeaw atpegv kedz wuo xa bdah.
Seo nuunr hbelu fpe guja ju biey suhe txim:
class StringUtils {
companion object {
fun normalizeSpaces(text: String): String {
return text.trim().replace(Regex("\\s+"), " ")
}
}
}
Kuu hov ofi a wuxseyiub ijmewp am yvir tuci ytigh do iypmezecc jsu mjuka-jmalhanh ruhomasoqy. Rcut, fii qaw yeyz gbid qipo bazi xeo liorq o ysemoy nazfzuel rpbaacluor wgi iss. Ik’v zleoy uxd waq wahz ngkeivjhsotwogz wauqkayurdu.
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.