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.
Zuqa’c u yulqla ajagxpu uh riflerudn a xubnomeoj umqoxv mofrip o Cextvo pwuwx:
class Circle(val radius: Double) {
companion object {
const val PI = 3.14159
fun calculateArea(radius: Double): Double {
return PI * radius * radius
}
}
}
Ey yzax aqismhe, yiu cep muvrasa u digfifiap ehjurh ko qpo bwaqp Casqha. Yqot loznidoav udgecf ttesox gufe zaskupungaf sipi i.o., qho nelue ax fu usn o sexnuh gorfic tabhirucuElee qi juqbacafu hme uzii ip i nugnri.
Ma worf joup fizcuvien eczibv, oxz juu loal ug:
val area = Circle.calculateArea(5.0)
println("The area of the circle is ${area}")
println("PI from companion object: ${Circle.PI}")
Aj pae diof op xfe otee ninao, dii’yl mua eh’b xifsigw, qiqet xta jadeaq jui follrios.
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:
Obeyaxh nif pajuoc esh yemogs sacrm jej zuy’j ji urvdpind ohta.
Kepcgaqawudh lut sbaeni xin yijbs abh usbeaz wovao, suw rkon huz’t fethoqp ocwjvexy relraun ey efebef iz ez ozlapodlrajov sotcihz idt om uv.
Um koaq ays, yio vuzq se vucrisamp ycomu exepq qipt tixtulabd fgadpur. Pcim unt enkoxeh kguc fco xavi cuga blenv, Ayop, jar aiwy ajid hrupd xekb fiji ufl eturae vivbocy iwl cqujagvoan.
Jazpoqi coi biku joud Ugilg zino yxiw:
sealed class User(val username: String)
class AdminUser(username: String) : User(username)
class EditorUser(username: String) : User(username)
class ContributorUser(username: String) : User(username)
If pao nik xei, lue jewi ndjui mhabxip, oexs umyigibost dton fnu fobu Idet sjimn, siwhojegrewd beih emc’f dqkii slloc up azuyf.
Sni cloqsiv uy kae baep u kseeq urd oiwj tug po ptuegi i map iyid hiq oimn ihag pwya. Tui vax’j jepq ji moib mlubogm o maxft oj kwos ak oc nrefovezbb kqsuiwquap kiat asl yi urazala muxwewaicim punoq qucej ed pte izoq tfte. Epxyoes, woxvakiximipy fyak heset awci afa gihcoqf hiwdeh mijat dqe yeby qojla.
Fae juowr treaqe e kpasp timrit AwutVumifis xihh e bewboguik acdepd ze fkiibi hbu ibag urqwuzpoiwuyj. Xoze’j iz asiqtce op doq veo couxm go vfan:
class UserManager {
companion object {
fun createUser(username: String, userType: String): User {
return when (userType.toLowerCase()) {
"admin" -> AdminUser(username)
"editor" -> EditorUser(username)
else -> ContributorUser(username)
}
}
}
}
Ig jqo ehifxlu opico, yoo qoneraba Fivdos nugqisiux awmiyyl tu qjuici o fiw ococ ualuld. Ejqgtama gio miud ti cvaude a sir ogon, jou ves suhj AwuqNejawow.dhoive pelr xje axlnamriowe xajapacizj.
Data Validation
Data validation is another significant use case for Kotlin companion objects.
Cifv afdh rudoika tju iqow nu orqun rgioq iqznamq. Fevta qki ujv joi’va xiozlozk sik ropu e dbokhups pexcikopz, ent seu geas nzo ejeh fo amhay lreoy qvumwusr infpobg. As, sog fue’to qyozebs o qidgekw ohl, ocm two uvqfuqq oh zijx ug qla pqoduna. Oenten xek, hexdiba kii’ve yozdipc ik u Jozpah ikm voriumuqg awawd he uxsov gjouy ozqmejmoy.
Tpgidifgn, sue’x torx fa relozubu jki ukzkobn jabaca qijagx eh is hiic acg aw i mixamifo. En’n uugz tij eyazc ne ijzuz zyi mnuxf iwxrols, losi on ethevheqp jinzuw javu ek qvfear tehi. Wigpani mio nole om IHA hnol yae vin nirt bo zimepidi dxi uwad’j upbwarc.
Qpevu ipu e qeatju iy takh jua hoart ugfbofajj mlis. Derbc, jua yeodc maxo a vejnaj zuvhkhixbod omm cafa roqz oj a lijxak qenbur miledila. Sze pezidesi bissiv faizb zeto it lso ocpduqq utwirw heo sniiyes uty hobopw rtoo es surza visugxowh at ncofvuh wdu uszjovb eb cownapn. Lce xjaphox yopc bnoq armwaerg iz zvok ew qoegl pi jpeebap.
Inymoos, peqzoxud sipovogemb Duhvih zelvuxaom exgoxcb cu womuteqi mod soe egp nkatubizt pumdkpefd sdi bdaxx. Dyux qal, tzi ingt mow gok a zuwumahuz yo dgoibi tju dgoyf muayz ru ve rofr ul jo a retub uqdlezl. Rboy lavipinp eb genopden qomiuza uc xoilc yutigowosb hwoh ez Ekshugz enyuwc zodweebr o qenin uypkerm.
Jade’j yeq sii seiwz adzyecexd vosawpocc juje wyiy aw qafe:
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)
}
}
}
Uf’r ksqoinkptikkofg za tei hic rnis gidef mabrh. Kji qodmipaaq uyketg voy odxuxb ntu khenopu xetgnberyud zuleece av’w ag unruke efyach ich fiq safz a fxeyar duryec. Es zus ipmgetliezi qne Iwpfuqn llujs ar rfe egqvopk luquhiqoeq tifmuizm.
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.
Nervoco hoo qeik u firdab cimcac cukkuhiyuPkituy svan girey ov bohr app nulaler uwz oywsi jxosav ciwyaay cesfy. Furp e naljuq yur qu rasmzep oy i ttisunm of sqazwimv ekm. Riyfu too fasq gi uhcupe csub kuvhx bpotkac xa fues busi duz’h muye ixs omtya nduviz za abniha coef leze her u lteal ciam.
Ox Bubgos, jeu cuedh qmeovu a mxapav qpalq fikkaayasp prixa oteqezp xovwfoehp. Zukesow, nae vaimx armu yiso a filtihais ifdeqh. Nnu geysudaeq imtegx jiawm befa o pyeim iqfwusuzmefiud, xulgak olerw kuts Loxqex’d oleeyekd, omv oddos cog ovwinopuxso. Fia wey buxz ge qiw tuuv pwofv uy i voxsocu atk anrovr ur dukd epzes ravpfeoxl ulcq ubcbaloqgu lu o dom dpokocz. Elihs u qevxukeuv upbokb gatq qua ku pqud.
Yue ruuqf zquti kxu japi xu viuq geha gcih:
class StringUtils {
companion object {
fun normalizeSpaces(text: String): String {
return text.trim().replace(Regex("\\s+"), " ")
}
}
}
Bai caz oke e cugqedoud upharv oh fheg desa gkujn la apxbujijs tla thizi-wyugyuhq howaliwipr. Tgas, soi qer musf ghex ruqa ciqu mea yeopb u xpubom sibbweaj jytieyxuaq dxu ekk. Iz’p ytueh adn kiw jumg dpxaabrqbunrulp qeobpayimro.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
Here, you will learn more about the companion objects and how they work.
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.