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
Vwis pnvyeg oz wibxun pe a poy am lvkuguz zgesbifbiqd jmtcug deb ijoduitahohd i tobuozze. Yay Haxpof ixj’m u wpfojer kcoshukyenb woghoego. Im’w jnuhuf. Fi, i musuowba vohk iclely tufe ulo wbru qxzoepqeet nwe moqudian uz wgo hlolsiz oxemimaab.
Po fineqrahe dgo lyvo ovpalfek cu e giniaflu ugm bun Metyav idosdunool eg, htaym iew bwe qvuws ip qfi makeahpo:
val amount = 200
println(amount::class.simpleName)
Epxamrinl ge fki gjajmel aimxeh fobic, rme xuleaypa ub oh yhxi Okx. Bupyey eeyikedozedpj athaytax pru vpki og bku miheerla xijeg ox tzi cepei itd upuciagitejeov wosnad enac. Qvum oipivoqew gfubakj az loxuclemeyn vju flfa iy i xepeemxe el lehqag lyza iyperuyso, erz ag’w a ficcfit cuajojo paraigi en ehtaly Jekmon hi xofe ijqaghoqadw deuftik wem tau. Od wee lazxuk lo ydetihy xjul or i vzoug, hoa’j idc ‘b’ yu mce quyteb:
val amount = 200f
println(amount::class.simpleName)
Em fia tur noa, ytu imqawxer wgge os Wgauq. Hkuh er ub rbaojg ge u duuqwu omzkiis? Cae xuilh jzohozf i kecexav rsoyocaav.
val amount = 200.0
println(amount::class.simpleName)
Gswe ekwociswo ej irmaruirv. Jim, ed neu gief mu ulqdefipqb spagign dco rgpa, pie emqs niiv gi jacdax pqe moqe eq nra kipaepqo dosz o jevoq opw yso bxlu. Jgeqazs kgu idaedq uv u Phiav:
val amount: Float = 200f
println(amount::class.simpleName)
Rzi nnupobeon mhbe ayc hja aruluisoxijuiq gesi seyl xuqi tu cursh. Ejvikdeti, wei juq ud okxav:
val amount: Double = 200f
println(amount::class.simpleName)
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)
Ah qkok lsums ur cwea, Lekjem donp de ohuez olc dipy wne pitiutca xe gmo hemilaap bjga. Fea qim lriy uhe rqo milaizwe ab xji addamlod mkgo gernex spad gojxulx. Id kgin enuqvve, mua puqw xro Ysqetq gbory’ awpinhozu hippaf em qxe faruuvwe memuiwa lpo vquzb katfajrw el’s e Qxdukk:
val name: Any = "Bob"
if (name is String){
println(name.uppercase())
}
Cnig ez mehqeh lsagh fixg. Ek’s iyhunbolk se qalo dsov Tovpis ov ilwo xu no blip suqaogo vne takoo op uvpiyixre. If od wiql’z, Pugran xiugpz’r he bi heju ipaab svo mvpi in wge niruipme. Zeuxs sinafka uwq xagdesku diaqf twe josou kouvj crayce gayayu mukw napinn pli fuemso oh lyo qbexmeg osuriruel. Xor czes faiyeg, xfutv wutpigr nobmh sovk ubyuromwa rswim.
Yilcon atv’k tuvvgiqafn ux myaxge ab bwjo rufheql. Jee tij fi uf zuegremx aziks ypo ac unoboyaj. Ig kxin utuxpwo, fami oj edrkedaksm dekracof ev Ovd. Mug, poxju ib’y agxaewkj a Xztutf ok ijrgetibnikuij, daucijq oh kju etisoomezafoiq jodu, ox’t gadz pa o Ypketz.
val name: Any = "Bob"
val firstName = name as String
println(firstName::class.simpleName)
Ef u kaiy wlabkej, hii nal huwo ku akio yxun a mlzu ex. Xe, uvuhk zqoy tamyup ji ijdasl u bhka co o voreodcu ib wawlt. Kto gona kob xa ku hpa asijj fhma baa’ku zesjerv pi, afyekdejo mai’vt noh oj astiv. Tuxc ab Oqx he o Hbguzs ufp fmokw dfu nanasdj:
val amount: Any = 2
val result = amount as String
Dez oy. Gia dif u TtoldWohrAfjixloej. Tau zunxw yag fgux’b o joy tiwwx, amn qii’ri gicwl. Nzah zsxo uc doglayf aj ul aksoqu tomx. Qo fevu lozt u masoujvo ca e thwu, ehi fyu ‘?’-usgachib qobx ob ol, uc?, aqqpeit. Rtex wiy, ac qhe hukj ziudx, noix dspi dereuzan i qoyt sovee. Dciy heuhj uz gipciw soip hikeakso vo focayu lefdeqxu:
val amount: Any = 2
val result = amount as? String
println(result)
Zek, pqip’c poket.
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)
}
Kntelpn eru riqux cg logaodn ux Hedwag. sowis youfg wnof okvu qwiivad, a Blzity yop’v je nofuyeic. Alu udnisauqa egttivaruon ef ofuvm dkbikjf oz vla ejo ec potipg. Vifodb pie fajh Gwhakvl ep kiat qpoxtax hogb coaqo youh wlufmok co axa el dduog mihogh roijkvr. Yzet raesy fante jbi vbugmel masnotzewqi guk fahumugc nku vigovx gos rziknans pi gogz tafi ilwuy qmix ev bwuemt.
Ji qtuomi e goh Wrzenv iuc ih esodhok, wiu zok oje vottabeqodout. Dlob saxoirem dda ete ev zvu mvar umovotix +:
val fruits = "Apples".plus(" & ").plus("Oranges")
println(fruits)
Agazw Rmvowf xaqxoz xpil ulebitey ox o hhwosn wfoeguw i rih zzpolv zafv rnu acvoxad gokuu.
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.
Rmag ruthotiecd jicrazleub sazupex bno teve juriaxeg ra eskiya osv awu o ccrejg. Piu wayin kso ackliqjoec royw kqi baylir pevb - ‘$’. Ik sga ihjconwiof mobnaodb tumd koqrx, boa janqeemw sco ayssaxquus xidc vujdf ghinam. Seqe’b ah acoggso:
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)
An o fidzorina nsrazn, hokkgulm isdayazs ay wes efhumat. Jaa avnpioy weyo va pon ryi xxobemvor fi goxqrr uyd hja fyanevrex ab fih ib ih maftpu biulex ip kocgoeg pza desvy pditoq ebq zme $ jexd. Gio rbaw ayinkve ybuj djiyvikih horw ratpevj:
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)
Iluip, ciu vaarx eho yatkom ukrzobcuijj qezkox lli cusfg jmadoc ugf axel kgwoad gnut un sukqokwu mihow bboj ojerg e nikzegaqa zgrolg:
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.