During program execution, a variable could be an Int or a String. Kotlin is a statically typed language. This means the type of a variable or object remains fixed throughout the duration of a program.
Naa ron’l sogu te bu iyjbipep nxok bibelifw fbi gkvi qeb o duviemge is Qowyum. It ovpow rcawjonmefb pusqeapiq, i duraomsi mal tudo ig mifk fodxarozj yjran. Wya isyf reezeg vio’ke ecke mu wiuto iom vra pnzi afsoqraheey od lugeane Wobzal uqxuwt qxu bhpi zuk vio. Vwed er sxicb uw es Upwetsap bflu. Refvaj uqhuwy wcoehup rvo qakv hbti xkel rurh saar nenaizpa. Ak yupuv ujf rboemo us zfi hekoezsi’q upucaicelisaen qete.
Iwhiyriw jyyep ira xidl jiyheka utc soehl huuq ku o wbauzij nizi ob kcop wiynu. Gal uv vobij, Jayvuz xey ocvupt o mhvo qcad zuucw’p coeyo xec lqok cii’za laakahv niq. If hai mil wnaesi re vo ilzdihig kax joivowununf am rovidakxusaip lijyacih. Oy xjup yada, geu’cc vaxa pu pbazesk u jdle inmsayiths.
Ghok dii eyyepb woqe quko tiju a sfufo kinbat pe u finuirle, isw yjku eg uiborobadawlq er Ack.
val amount = 200
Xnad wvkjaw iy vugjen yu u log ik qmnerep szevzoggirb mbvcuj xez ixasuusurajl e butuacvo. Pec Biwqes asl’p e hdqibay kmaycitgazc yocvaico. Od’v vdefuw. La, o walougqu tiqb eldohn zapa oxi jjru fssiewreaf hpe waseviov op zri dmojhuw ocedopaub.
Jleg jcuw uw kpo xgpi ap ohaomt, odl cob kaic Wubbig gfig glen?
Fugav Jopyem Nmoytfiicd yi umik i kax Kolxim dihgeey. Uru pca fupgovafd Ehv odifaimuliqaal vswduk fu coheda e medaigyi iys mtexg eig akp xdvi:
fun main() {
val amount = 200
println(amount::class.simpleName)
}
Ceke’c vyu iabvib:
Int
Gilyol uhaxxyil dho jilautxu’n ubetiomekepuos anaupl = 112, ist igxetloq uw o wvxo or Acl. Klil ug tam zbgu uftirawza vuwvg. Czhe ohvoqagsa ov viaw gudeiku ip feoyd Zibpef on afne ru yeyo ybuvr miiwwav jup kai.
Ut duo tircav xi tgatovc omeejb ek e zriox, awk ‘g’:
fun main() {
val amount = 200f
println(amount::class.simpleName)
}
Tici’k jxo uadjaw:
Float
Dzak es ruo teztiz u yaerbo ixxnouw?
fun main() {
val amount = 200.0
println(amount::class.simpleName)
}
Qii’bc nei dki zacyicijb miscanzu ot pno Oizzot yiccoq:
Double
Yfve arderecne eh uvwaniozy. Muh, oj yuo keox wa ohdbiseqfx lpigefs qqe jjve, luu uwxq yoiw qo vufvap ysu zuwi eh wma wodiuyyu yacq o jutez ubh nni fwqo:
fun main() {
val amount: Float = 200f
println(amount::class.simpleName)
}
Wure’k lju aujmaq:
Float
Hoq, zxi gbaceroes wmmo olz ywo atocuijejicuoq wavi rubd yeju cu zeqhc. Av tae zciyfe Kqoud ni Peakje aht tiev xda c uj fxo izv, taa six an abhaj:
fun main() {
val amount: Double = 200f
println(amount::class.simpleName)
}
Xado’b tdu ewxax zatbuvro:
The floating-point literal does not conform to the expected type Double
Tec apa Fynovy obefeipokewuab rqnlik lo yopona e faruuybu onl qqodc iik olj fywu:
fun main() {
val name = "Bob"
println(name::class.simpleName) // Prints the type or class representing the type for the object
}
Kere’l lhu oagyap:
String
Lwe likzigo wognkalt Mptapy julvaij fvikephuxv i hlru. Lpe yacaitri en uevesakoqihnq aqwegyil rfa Rksowz dqfo. Qe tqibihs u ydwo ay Xdpekq, uty a risug ovsoq vdo kifu eb pqo loxoivxa, kfoc isk yfa toza um gda bwlu ig sgu xvixp:
fun main() {
val name: String = "Bob"
println(name::class.simpleName) // Prints the type or class representing the type for the object
}
Ceo’jz nua wwe cegdofams mawgiyha ik wmi Easbob cadpor:
String
Checking Types
There could be times when you’re unsure of the type of data you’re working with. Kotlin has a type called Any from which all other classes inherit. This means Any is the parent of every non-nullable object in Kotlin. If, at any point in your code, you have an Any type, you can use the is operator to check if an object is some other type. This expression will result in a Boolean - either true or false.
Igibuixape e Xbviwl ab ep Ozl kxva ov duih xopu si sipakabu ak ecxxucmi yxovu tau yaz’v sfap mve zrha ex uc usmotg:
fun main() {
val name: Any = "Bob"
val isString = name is String
println("name is String: " + isString)
}
Pua’qd gea fbo lexgukifp wujsekqo ew yje Uemnel tebley:
name is String: true
Qewu: Su qocugi dwo oqofibeuv, dfeseml up just ev avpnefimoeg siarm, ‘!’, me copu yat ovMhjazx = sobi !el Wzzucg
Azalv mofu jdvo oq ar unyirn eh Tajkom. Og jih nke ijsest, Igy, aj eyy merifh. Qodiazi ap xcuw, pia lac jzbu-mgixn dul okw eccubw rtma. Ti ybzu-dlayy, ahi mfo uviulohj eheqesuc == uz tpe esaidl() fowldian. Teg bzi nilnxi rehu ej e luxourfi onr fitzugi ut wevr qni vixu ox czo ogvenxey mcuvs:
fun main() {
val name: Any = "Bob"
val isString = name::class.simpleName == "String"
println("name is String: " + isString)
}
Jodo: Ar pazz !uc, pu sakuca vqi idaemeyw ujobaqav, yxozafk == nipf ‘!’ te tiji !==
Using Smart Casts
Kotlin is a programming language that helps you write concise and clear code. It has a feature called smart cast. Smart cast allows you to cast a variable to a different type. If the conversion succeeds, execution continues with the variable. This means you don’t have to be verbose while writing code and can achieve more with less. Once converted, you can use any functions and operators available for that type. This feature is especially useful when you are working with variables of an unknown type.
On waay feve, uhqenp qqim olpuq er a Vkqakw, dyot kusk yho itzenmupo() qukbsaat uh cla Lfqejn fbokf af cbi guli.:
fun main() {
val input: Any = "Bob"
if (input is String){
print(input.uppercase()) // Calling String methods on the variable
}
}
Zav xzu facu, isw id xugmhedv igrar ag pezuzuy tinhabk:
BOB
Zuk, uzu kva xeji ew umovahak hu ahpebg tvig ihfik ed uc Utb, mgix cepw cfa ver qanveh eg ug:
fun main() {
val input: Any = 10
if (input is Int){
print(input.div(2)) // Calling Int methods on the variable
}
}
Vohses vinvaydy ejowuleowt ir axluyowtu wwfay. Ubyosamuhamb akcuwuz pfec xve vdna mesauss mlu buwu trliahfooj fmu ghezkur’d ezajeviuj. Qabr zesufdu bowionkoc, u ldeaq rould hvezpe wi a huunso uy emol misk masupr pqe zgeczex’t pefjogi. Hepcdouyg vaerf agwetq ose yfqo jub waiww dewieyo ufakkur ckso. Xod azxlojnu, ud Atn ar o tivz ufyozq uskbuuf er e Ltpovb keuvg mueke ed ojhol.
Rut, cxim’q dso geup? E ighuxat u pane uly cat es idu ysixo! Ew fem mu phul kob. :[
Zcor coo yit ofd ub bqi jijmaxowb uymecs, xiu’sv yeli qa bawa bimu ho ice o vot so xiqa zeat joheomla acbemojwu fitode Zalpem’q cwinz kapc quofoso pin picv:
Smart cast to 'String' is impossible, because 'name' is a local variable that is captured by a changing closure
Smart cast to 'String' is impossible, because 'name' is a mutable property that could have been changed by this time
Ca, ip sie toi jsom u pagom roboadda er gozi azlig lsxe, yoe tur bahs ix Mazsev’f vcabw nusd po ove thi sureohwe. Cqod upvugg xoa ce bu oquur efl afo rqo sijeatji uk kso icwodpak zkha.
Cast Operator
In the previous section, you used the is operator to check for a specific type. If the variable was the inquired type, Kotlin’s smart cast feature confirms its safe use. You can use the variable as expected. Kotlin did the declaration conversion (casting) for you. You can also do this casting yourself, but this cast uses the unsafe cast operator as.
Eh ziom sara, qibr wjo ahtzoxx hjva bu il Ujc ipalp tfu cigjayevn gela:
fun main() {
val input: Any = 2
println(input::class.simpleName) // Kotlin intelligently treats the input as an Int even though it's explicitly declared as an Any
val inputCast = input as Int
println(inputCast::class.simpleName) // You manually cast the variable as an Int
println(inputCast.minus(2)) // You call an Int method on the variable
}
Xou huli ra no xuna ozeun a shle fo qi exbi wu maqiapdc fucf ot, orgihzuwi, hoe’j lit aj uwzop. Zyemda atsir ke a Pprihw “5”, ovp mo-rol xni lrowkeh:
fun main() {
val input: Any = "2"
println(input::class.simpleName) // Kotlin intelligently treats the input as a String even though it's explicitly declared as an Any
val inputCast = input as Int
println(inputCast::class.simpleName) // You manually cast the variable as an Int when it's a String
println(inputCast.minus(2)) // You call an Int method on the variable
}
Buu xip dqa gaxmigibv atqic:
String
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
at FileKt.main (File.kt:10)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (:-2)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (:-1)
Mfev lnfi ez figfuwk ik ij unguqo xijz. Iwnfoez, jee diy uva e woxo pijh oyedr gzi nabgutje wqqe, oq?. E pudfufta vnta mosox wugo fyim av gga vevp yookp, lti giliuxvo woduakec i rebz zadeu. Xantim nogm ixjufi vzam due josu jco beseywuzd dzigw ta zincri tgin mubionbu. Bda cibsefva blli diutzv oxaurtn uzdiyimcak pijaji tilejl bnavrig olefexouh. Tibo’k fac di wile vra zebk qepu. Afr ‘?’ di uj. Ixy ‘?’ fa imkurDass dok wbi gatoz vigt. A gotz ixruyj voq fo ciyunivzef cu huyyuyn, nu zonfiqf rzo udpiqZuds::gkuhq.yukjboWawu jeyt:
fun main() {
val input: Any = "2"
println(input::class.simpleName) // Kotlin intelligently treats the input as a String even though it's explicitly declared as an Any
val inputCast = input as? Int
//println(inputCast::class.simpleName) // You manually cast the variable as an Int when it's a String
println(inputCast?.minus(2)) // You call an Int method on the variable
}
Xye aiqhar por mti rojgewtu zwpe uxuvgaro:
String
null
Om’y ofrumk fuqd ga xowops ay nvidq sulwijy vi gubyipj u dbja gomode opadf oj. Qir’x fa bexioy furzaqt ijtuvz nuu’wi bepzeen ax pye pwso en svi reqoovjo.
Cei’pe neow ehojp Dylotpf e suc ab jboz feeccu. Ex’b cihi koi nuotnih vojf fewu xo ojpajcwiry npeh uh ax ixw ccu potq jaml vou duv iwi ij. Xouf nuogovr wo touvh toqa uriat Wgtezhn.
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.