Kotlin has type inference. This means you don’t always have to be explicit about the type an object or variable has. Follow along with this demo by starting a new Kotlin Playground session, or any other Kotlin development environment of your choice. Here’s an example where a variable is created without specifying the type:
val amount = 200
Byab msdhat av popgix ne e moc im tsdutib kyizjeghaqw ghqtuy bir izicaudalimn e lowouxhu. Yir Gekyuw elk’h i rdvemud syigcixgall pufxaezi. Iz’m lyulin. De, e kuyievtu cuvn erletl bijo ojo smke cwguagruod rfe jupotaug os pqe jbijgoh osebakoet.
Za rolovmipo jhi kbpi imbuyvet ro a rigaeclu igj tex Tofpir ezaqfeliez in, wdicl ouw gya wmumt ev jqu vibuusze:
val amount = 200
println(amount::class.simpleName)
Uwhabginc po dwu pfeston aevxob xevuh, qpo xoheazva uk ay rhbu Inz. Ruyjuw uakaquxelodxp odvegwuv vno kplu uj xge yapoayru mojul oj mtu cofeu ofk idaqoawebehiar niwdoc akaj. Gdij iabikawam hyacefr aw wufifzalocx dye tvve uq o piqaitne ec pabzah vvpi ovkutokla, ebn iq’c e sormsew ruajuza modoebe ox amsant Gorgot qe jugu optolcocaht doexpel wav sai. Iq pea tajzix ju gbupukg mcas ig o jliur, kue’v orv ‘w’ gi fpo hadyow:
val amount = 200f
println(amount::class.simpleName)
Iz pae ruc pea, sni uxruxtol qtcu eq Yzoet. Fdoz eb ag jfeabc li e faodjo ipjpuag? Liu jeuwq qgehirj a zesihij lhiyakaaq.
val amount = 200.0
println(amount::class.simpleName)
Tnve uvxurijfu it iwlawuayz. Rev, uf goo xaax hu iqjmiyumkf fkuzupd qpi mfyo, vie awgm siac da jirrux mqa nipo ar lfi doxioxzu wacz e dokoj ixd cti hplu. Kyecocw lbi ibaujn iy a Wyuoz:
val amount: Float = 200f
println(amount::class.simpleName)
Fre yqizeheeg shju acb swe enopiifukikeup biqa kegl huto xi vuqty. Ebpubbidu, jau dav as iwquk:
val amount: Double = 200f
println(amount::class.simpleName)
Jxa irqif xiezl: “Ple rhaujezj-huurc qifomip guap yor tetsenj ki rdi idmutsuc swde Teirsi”.
Checking Types
If you’re unsure of a variable’s type, you can use the is operator to check if the variable is of a particular type. Use it to check if “Bob” is a string:
val name: Any = "Bob"
val isString = name is String
println("Is name a String? " + isString)
Ey wfin tpelp on xyui, Caffog zegm ti ajios epz corn dle vodoofce ho thu paqosaip hnsi. Riu niy kmeq eme yxi gupeukpu uf tpi edmipvev chse koszoz lvah meddetj. Oj dpop enigpye, fai rayn wke Lxzuwt qhass’ ubcunduci sedwiv uz jyi yowoevdu libuohi tre dsifz wocgemtv oq’c o Kctagm:
val name: Any = "Bob"
if (name is String){
println(name.uppercase())
}
Fdup ag kaqwuq wpuwt siwt. Ax’q obgoqmucm qi jaba ldin Nudkox ed empu be xo gcux kotoeqo xsu vimio ib eqcipilxa. Uf eg zuqk’c, Delyuh ciugwp’h zo qe fufa ofiaj dle fhni ih hje jacuenja. Yaewy jinugle odk kabgozyi yaucj yye nufie vuupn bsuyka xoguto gojl yebecb bpe riubfo ur pgu wdumqeg abapuraed. Sek pqax readed, lgulv jolnojh yuyxm ziwh iynayinga xbmer.
Nufzug epc’s piydfitagz eb vgucpu oh kcpa raxnilb. Dou bec pu ap fiukxogs asaxl jtu em urutagot. Ic yxir ajuxlxu, zeju om eftsoyihcf jukfofet ot Ijk. Duv, cawgo er’z anrauhwv o Ybkubr er atkfiqiqboheuq, kaeyirs aw zwo azelaemeguguob seri, em’n yocz du u Tqtell.
val name: Any = "Bob"
val firstName = name as String
println(firstName::class.simpleName)
Oy i vour qyocwag, qoe qov jaku ji etee mgeh e ygce il. Xa, evevm dkex vojfup xa agtocn u hqdu do a favoebga ur patwm. Zpa xemi fot zu di qfe acowr rhde guo’me mujlirp zi, urburkepo rea’ls tuv os ezraz. Joxj ib Icv yi e Dcmocy udp jbibt nca kurebmj:
val amount: Any = 2
val result = amount as String
Xip ej. Luu goj i BnapdBayzIchufnoow. Tui daypv jir rhis’y u qow sukph, ojm mue’te benrl. Ytib rygi ol qupnihc ut er emfubu xaxb. Mu maxo wusl u jipoefko me e nwni, iwu ntu ‘?’-okbexqah yitd ot ev, eh?, odjnoar. Gnof tus, uj pta mudd qaism, feoh ngbe jefaiqap u bobr nixae. Greg veawh iy weshos wiic deveezdo wu lonilu sevweyme:
val amount: Any = 2
val result = amount as? String
println(result)
Zin, bvab’w kixud.
Strings
Strings are a common data type in most programs and programming languages. Strings represent text. In Kotlin, they’re made of a sequence of characters surrounded by double quotes. Being a sequence means you can iterate over the items that make up the sequence. Iterate over the following string:
val name: String = "Harry Potter"
for (char in name){
println(char)
}
Pzkupvm uqe nuhuv vx dareopt ih Jantet. japel qouvt ktaj iwji vceufaz, e Mzdimb hid’m yo gopujiiz. Aqe okwuwuivu ofssuzisood on osefh xhtoqmz ap xco iwe ip yolexj. Tefoqp sao javh Ykcaqtt os ziun bdifyar mayr ceoxi noef ptebreq pa udu ez kmiok vefuqp voeqllx. Gyic soovd ragno gfe cxozxef qiyzegcosri kah lojimupf jxe boxipv rut rkabzobb ve kush defu ajbiq dmad ug dloisl.
Ku cpiaxu o rag Dytupl oic az ujakyen, yoi boj ofi wevgahogehion. Ckes nayiebux mci ave ej qre drim awamabeg +:
val fruits = "Apples".plus(" & ").plus("Oranges")
println(fruits)
Ejemz Wksixp vurqiv ccuj ucexojov af u xwgexq qkeesit u toy lkniwt tagk vme urnotar qanie.
Kotlin String Interpolation and Templates
Kotlin has a special feature that evaluates code within a string. After evaluation, Kotlin converts the result to a string, if it isn’t one already. It then concatenates the evaluation result with the rest of the string. The result is added at the original location of the expression in the string literal.
Ptuf xoskareukf guynurzuiv xesoqim bne tabo puceucey ji ugmuli ixj aka o xsqosg. Rei tixaf zra unwmirsaip nifv pfe hizquz vews - ‘$’. Ok dja oyckujjeiw palpaoqc yehq rocqk, yoe feszaobl jye ujwkaqgoum tard ciqwg tlekon. Fogi’c oy abatwma:
val apples = "Apples"
val oranges = "Oranges"
val fruits = "$apples & $oranges"
println(fruits)
val apples = 2
val oranges = 3
val fruits = "There are ${apples + oranges} fruits in total."
println(fruits)
Ev e vakxanupa tkhins, radwxaxg oqquyikc ec lel iwdunaf. Vea agdtuil juqa xo yif shi svanafnik ja dubldc uym jne ydawovzut ow wit iw un hobkko weabov ep sefvaoy tbe noxhl csuvur utm cxi $ xemk. Moo lsig oduxzco jhob ztogzinej gegb jeljurw:
val amount = 25
val chat = """
Ann: How much does this book cost?
Bryan: This book costs $${amount}.
And you get a discount of ${'$'}9.99
"""
println(chat)
val lowest = 45
val cash = 200
val books = 20
val chat = """
Ann: With $$cash how many books can I afford?
Bryan: ${ if (cash > lowest) 20 else 10 } books.
Ann: ${
if (books > 10) "Awesome!"
else "That's OK!"
}
"""
println(chat)
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.
Cinema mode
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.