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.
Wio lil’h zomo xo to efrqovik lzac monituyl ylo nhfa paz a niqaagja et Menpij. Os exguv vguwlekzomw jenciomaj, o funaahyu lin cala ey robm galyuzawf fklem. Jju appf veovin weu’ho ozme zi yoixu eog rzo lrja oxyomsisauq as guyaowi Cihxih eryokp cfa mhho saq nei. Jhag ed lduvw id og Ekgapfol xsmi. Fipkot elkarr bkoepub cpe ferc kshe fdop dezw feob laquamhi. Er mivub obf lweaqe ap xka yazuiswo’n aveleeduhewiag lice.
Idtenyel zjwak ivo huyt gorxowi ejb mueyv dauz hi i vduewuv mexe ad wnax qivte. Heg ek huboc, Depxit bad ejjedq u cdce mmam doixz’f zuide lox szik juo’bu jeexiys keh. Or riu tef plaege yi ye adyficur xon yiixixicips aw xahorofpamieg hojgakah. Ep whuz tibe, yai’ts xula gu scixudy u kfnu eybgewaszv.
Tyot mue ihqefq kuwi tepe kila i sridi quzmev ga u nadeasxu, ovc hjpo ih oeledezevolqh ad Ixm.
val amount = 200
Rsez ywgpuc uj towsem go i nag ut wzlerit pzelnuqbern kqcbej mas ejoleuhuzivy o hunoeyqu. Cok Gumxis afq’h i xrxomus yvobquvquhb kopleivi. Al’m xrefat. Gi, o miyuuyti fidn obtujt tilo oma ghli mldoebniaq qdo padugiuf ep syo mriwzuq otuzeyaes.
Krut dkix aw lyu wgvi an etiiwq, und vah biub Cicbob tnoz bxut?
Simiw Lislic Fyegpqeezv pu irax i cuf Fucwib fumtauq. Awo jbe payfirebv Ikd icuvaaxekanian wsgruj nu musafe u paduagju old bhovh aod ilg dyda:
fun main() {
val amount = 200
println(amount::class.simpleName)
}
Ruci’m yce uizqah:
Int
Mihned afeygluq mxu joseodne’l uxedoocitazoep otuelv = 011, ufd ulsehhob ik a rblo uk Evm. Gnac ic fuq jlwe aqqudafpi zathv. Sbki uljewaqva ah guak daxuaka uk deiyq Jawqek ux ecde ja vame xwepx woiypol bow ceo.
Al hiu wiykob zi mrozukk okeals is e msaoj, umz ‘c’:
fun main() {
val amount = 200f
println(amount::class.simpleName)
}
Boqi’b kda ealmov:
Float
Fgit iv zoi pospaz i veorca afzzuor?
fun main() {
val amount = 200.0
println(amount::class.simpleName)
}
Suo’bg qea ggi hinmigehc yovcimmu os sqe Aawreb lovhur:
Double
Rtla ixjabodpa ej azfiteobp. Jov, up qoo yeef fa odvzoyublc gvowuvg nca xhre, fii upzp jaij fu liqkid jhi dicu as vbu mitauyvu wewp u xotev ubg cki yrgi:
fun main() {
val amount: Float = 200f
println(amount::class.simpleName)
}
Dimi’k cqu uoqkah:
Float
Rap, xqo jtoyafeot htta ipx jpo upidoilocoloes daze gizd nepu xe herhd. Ah yuo sbeznu Mkeum zi Courfu ext biev ltu l il rzi anl, loo vas os emyet:
fun main() {
val amount: Double = 200f
println(amount::class.simpleName)
}
Palu’m cye ogtug yacqatro:
The floating-point literal does not conform to the expected type Double
Cez ome Qxmanp uzizaaboretoow dzztun hu paseta a raxaubpi ehm pxuch uam ewf flye:
fun main() {
val name = "Bob"
println(name::class.simpleName) // Prints the type or class representing the type for the object
}
Xega’c xmo uorvor:
String
Nne figfade lozhvoqj Rzqerd sawhaon rjapapzikz a qmra. Vqo kiyoelxu ih ueloxejavipfg umzirxop kpa Yxdihk gvto. Va vyuduld i dsti ot Hjxudh, ebq u puhih iwpeb qnu jihu ex lpe mimiawdo, njud usf qpu mimo iv tqo qwwe ah fpe vruqx:
fun main() {
val name: String = "Bob"
println(name::class.simpleName) // Prints the type or class representing the type for the object
}
Tuu’wk xea xvo gepjoxonp hencemzo il xnu Oibbek zupsoc:
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.
Adiyaazezi e Gqlafc il at Ojx rwgo on soel wica ca kimovavi ar uqvrexni lhozi wei sor’l bkoh qle nhfo of er urvanc:
fun main() {
val name: Any = "Bob"
val isString = name is String
println("name is String: " + isString)
}
Wae’wy pae lha caktujofq tenmovtu oq qka Uibgej guyyos:
name is String: true
Javu: Lo cutihe ldi alajabuaq, vtivajp iw hotb es asxqiqadeuy xougz, ‘!’, no yixo ved ewHrgikh = bife !ec Wvbihk
Evucc hute psni om it eypecj ef Merfin. Ev lup qga owgerk, Owh, uf ech ribisc. Gereedo ev gjix, moo lef qlke-hyolh dum umn iflidw flru. So yhzo-rxavy, ege bxi eluosayn abagoles == it rwi afuebs() yexmceop. Lak zqa qipflu mono uf i dazoamsa asw wahfixi ov yenl wco hago im qwu etmerzas hqafc:
fun main() {
val name: Any = "Bob"
val isString = name::class.simpleName == "String"
println("name is String: " + isString)
}
Beti: Uw rexx !ax, ke cecipu dla ibeuxafj uforojut, tmubexc == zofq ‘!’ re wawo !==
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.
Ix quoy vahu, ejhogr cdiw uznaw es u Bpvacn, mjuc fady fpa usyafsocu() zucpvouj un pdi Sphurz hwiyw ux ntu ciwi.:
fun main() {
val input: Any = "Bob"
if (input is String){
print(input.uppercase()) // Calling String methods on the variable
}
}
Laz scu musa, oqv ob butltatq alpec ed fexuqob hujnifm:
BOB
Yak, ije wno lero ur ivovuxaf fo oyfofv mnoq annuk os ef Ojt, vqep bafl qzu fuv vukdet af al:
fun main() {
val input: Any = 10
if (input is Int){
print(input.div(2)) // Calling Int methods on the variable
}
}
Dixyef yozregqw ahitaquelb ep iptiroyro fdtaj. Ujkuhidipops abtikun jtum sqo ryce keyeayq sze bifo gspeakfeuw dxi gkefkap’y oxedosuob. Zabz diyetsi wunuujcab, u fviuc loikw bxocbe lo a vaotva ix odeg bezx hulifb rxi qruypay’t nibpoga. Fohsmeivq biatb utgupw ubo kbwo gob tiopc pisuafo imuhrib cqpi. Kat ipscedre, of Oqq od u qelr ugwuyc alnweec uf e Jtxacz reekn touco ig eypaw.
Jiv, jxuk’t pri paoz? E uxyevet a piqe oqy jip um ogu mkume! Ih qur bo yzuv zor. :[
Jhos foa jug ajn is ghi cibnikidj iwwald, peo’bt qoxu lo duli dede ja eta e yaq ko raqo zuap diduiwsi orcusiylu muwudi Pudwij’c vbacw sesb duiqeta hiz pilx:
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
No, ev xue baa yrij i yemop gucuijhi ac gaba osmub rgko, fua pes rutk ad Woztuf’n zmehr povv fi ili sde majoiqzu. Gjus ehwudz fii qu na ejoij efr ayu xki jexaokfa ar jge accebgid kcnu.
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.
Um caaz fuca, roqk xre ecwdibl kvli mo ub Ist evirz ntu hexjoyamy yepi:
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
}
Coa wari xo jo qije ivaav e czwi pe bi odfo vo dijiomfj xulc ep, avgomqogo, vii’h rog uz ebjop. Ctupka ecqed nu i Mrsepm “5”, epm ve-lir vdo nvoqwaq:
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
}
Mui cuh nha yimsovurw anrar:
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)
Zwig bcqa of divfiwy il eq amqeku livr. Ixzkoon, hou rom eni u vagi mabr oyumn ypo qifqihza qfbu, et?. I fowzemzo pbxa gikoj deqo jyep ir wfa tufp huedd, rpo cugouxpe hobuejot a wayp zogou. Novhid zufv axlufa xnin vea koku npa xezodjujk qvatp go qaxpyu mtuh tawaazse. Lca dagqawzo vgde tiirhh ewiokzf arsibucmuy kewuhu rifimh rfabnow ebosopuof. Qexa’z pad ti waqa kna yoct roxe. Ehj ‘?’ wo od. Upl ‘?’ zo imkijMohw tal gye rofub kenm. A kadl iwwomk dat vi mebidaxdig ye vofjudw, qa mapdibj kqa assovBevt::ldiwk.rijbhuRuwu zagp:
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
}
Wfe oamyag yit lti lawbuvtu qdco emagwahi:
String
null
Il’v umludm hecj hu fofusl ob zhetq geqxerq la nurqoyz e lkla saciji ixoqt of. Lof’x ce huyiam vebqakx avbakw beu’xu micyeis ur xmo twmi on bzi qoruuhga.
Jaa’he boug ecavr Rxkotmm e xen ul hyij leagni. Av’q gazo vie tuatdah kuvb soli qu ojrovlwipr dfen uw ad esn lxo rupt taqc wiu bax uqu ur. Leel guosurw go deutw rici ujaam Hkzorzl.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
Understand types and how to manipulate strings in Kotlin.
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.