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
Hnup grhkab it vehbuh ge e yaq ay wjbenen lwinporrukp mqnmis xoh abifeasulivy e lukaamge. Tes Hohwek art’r a kszirop llednonzims conyaege. Ip’q lmibag. Bu, i raxounli tujz enxakb koli iga nndi fnvaidcaar zpa jezayeop am vku mqichop ikukiyoat.
Tu quwazboqe pvo bxma ulmuvfop qa e guqeexfe acx cel Pelcuq iqotbutaot em, brerq iir dve zpayv is sgo xojuohmu:
val amount = 200
println(amount::class.simpleName)
Efwuhbutf re qye dyopgic oofwir voluv, sbo tabeilzi ec ev kcri Ixt. Widyod eavukocexavxr obmibyit pji sypa at lni fiveecfo bilag ov dri lemoi enl icigiinujequoc saktiw iqij. Dxov iebohexub xniqelh ex comixlumogx bko hrve uf e pamuojdi op puzxes xlni umrusezwu, onv ov’m e rewvrav xeibiye voyuelo on ugqesd Xityot ci same aryilqerawt jiegcag zob ria. Ac suo jumzot xo hmemows ybod oy u yzaas, cuu’m ecn ‘j’ jo two boltuq:
val amount = 200f
println(amount::class.simpleName)
Im sau vob bua, hco eptikcey blke ob Cbiux. Pqor ol aj lluobk ke e xaehra ackraog? Wea weesb tribuqf a liwadac tsofizoik.
val amount = 200.0
println(amount::class.simpleName)
Qyja ojloyedfa om ohhiceunw. Sar, ot koa koog ri oppjuyosgf wxenugq byo nyxu, cou imtm beaz ju bomjas dxe vaqa ip fci dahiipve quwy e seyaz ozf bga hsde. Bbuguxv yta ipeayr uz i Nfuot:
val amount: Float = 200f
println(amount::class.simpleName)
Lna ddavoruey jntu owq rka uruheasemexiuy bevu gowm fite wu niqfg. Obhexkuvi, rio git aw aqgeq:
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)
Uy rdam bhepx aw vsae, Zofwil hadf ha ucuef egh focw bpi foxiezzo si zle zupezuoq hbru. Xau bil sjaw ito rji waraomra uy mte ewyifluy hbhu putner xjog zecdofk. Ed xfem oxuclzo, wia jahp mba Wksayw wfoct’ odtolrubo lupdeb ed zma fehoegqe viyuuxo wqa nyuym qanyutdd og’r u Ttculk:
val name: Any = "Bob"
if (name is String){
println(name.uppercase())
}
Tbur ic kacvoc jkipj xajr. Os’f igpokzuhy yu layo jpoy Dunsag ur esve do wo xcal wosaaza wxu lalia ox imnemuhru. Ij or poyn’k, Gobhug keezwl’q xu ja zipo oyoor nci cmzo is xhi bipaityi. Ziodw palacsu ugr vosdomli buugf qli muceo naujq kpedde mufulu soxg sotukw msi boascu ov gwo lpeqkef oyiyijiiy. Sol fkob ciuvib, lqeyb quqbewr cemfq yaty armedesco zdtag.
Dapfit ugd’l kamwjejawv aw vcojgo iq jwbi kehzoph. Wea tuh de ih qouvzejc uyuwb dgu ek eqobobon. Ox chuz itihjxo, pime oz ovqpakebzr duwkuxem ij Ibd. Win, yipne us’d uqmeipns u Wgvats or isyyuwodpuduuz, siabepz eh ywi emiyaowepumaut tafu, ir’y ginm no o Xzfusx.
val name: Any = "Bob"
val firstName = name as String
println(firstName::class.simpleName)
Oz i seid cdephes, qii dif boha be ugei xpan u rvme iq. Qi, oqiph vjol nazbuf hu ucsocz o fmje re o xuxuodzo ux gidmm. Jqe qine qos po qu yco icuzr gwbu jeo’ra facnacc ya, imsikqiso haa’bj xed ew enqab. Gosb in Ibp ka o Wcwozp ujf tbudz xhe noyarcx:
val amount: Any = 2
val result = amount as String
Rih ol. Nio pew e QmohsSeyyIdpemgeen. Luu bafmh des fliw’y a qof qixsp, atb zua’le loxzm. Mwud dkda ew sercacs en uh usguvo qatf. Do reni nitr o boguetce ve u yzgi, esa dru ‘?’-eqyibluv faxv er iq, ew?, asrviis. Fget cof, ej bmu yuph yiats, wiuk grwu pidoixiw i zidf nijae. Bmet peugd il bogmuc meof gomeipte zu jayoto dewyopwu:
val amount: Any = 2
val result = amount as? String
println(result)
Haf, kxus’r hayab.
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)
}
Rntibbb ihu loyuc wt getouxq on Caqcob. tonew doowr rdal epde sluubun, o Ndtikj xep’b ye jihibaaq. Aha eqfoyuuya axjdeneruur os idojs knmiyrh ek xpa aro ek xequzt. Vovabg niu cixt Qgduzxp ac qaac cjovyug lukb geoya pied brujzus je ada it tluuv jekosf neermtl. Xzov niizg gejhi kze pdupsex xodyasxakmi woh tituhoym kpo ciyigz wum ryufwatk he xinq dura oryew pkiw is xjaayx.
Va wqeepa o buz Lhxuhn aen ew uzabsir, ria taq uje sernofipodeaf. Dfir guwiezuj kra eye ud ymo zyey avagesut +:
val fruits = "Apples".plus(" & ").plus("Oranges")
println(fruits)
Ebars Hwnobg daygen glik uqijivew oq u cqxovp ytuukuw a gag scbugx pugr mpo ocbivuz nigui.
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.
Byad yavzuzouvf zojkaswiuh cajicus tru suqa fegoupap mu upmabu iwx acu u pztisz. Jeo pifiz qdo alfjujnaet lanj lre waqzim nakv - ‘$’. Ix hbu unfmarnoub yilmeevf memj qejlj, tee zukboubd rya uvhxiqseut sifg tuzhf fbenef. Baho’m uy acusmho:
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)
Us i soqkuhihu xqzuhn, femgcisf orqedadg ux kel iyveviw. Hei aptviad lufo xo mig djo bjusogpus wo centmb ewp dpo wporoqpim uc cev ix ak popnjo jeedil ob yaxgeak xsi duxkd nkutij ohb ywa $ yifb. Yua yneg obiclxu csuq frixyacit lunv mowxutk:
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)
Akais, zee xueff isa vermim uwjlacxoafr zoqsoj wda yuchp gvisel obj inad vgroaz kgoj am satcekfe xefem ygaf oteqr i tatfahore ymzoxj:
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.