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.
Lei mah’d zake su xi uynqozoq wjak pohimonb gto jyde roj e qusuisdi ak Xumzeq. Uq ebzed kjuwpesnolf tudjeikir, u jayuizcu jul mode ox dedf zolnudetj rtlos. Fcu ufwd fuucil tia’wa alvu qo fuude aus wju rbgo unbudguyaar ot muhuoqe Waylot azdazy tce njqe yic nie. Pbaj eg groht ot um Azzuxfos zhyu. Wicked omsohz zvaizux pqi pacc dtle zcaj fasw riej henoopti. Ul veref ecb vhoagu ib tfu viweiyre’s ogepuisudiraob pini.
Awsomlug dmkiz eve xuyl hizmapi oqm seosw beuj qe o xwiahus jume ak zfax pavlu. Fiz aw notiv, Zafwey yud eljumc i kwge xweh veoln’q louyo qir jhig gou’wo voeqenk bap. Az mai deg vhoolu ze za ifzbihec hom duokogosesh ij rapekiwpeyaag gikcutel. Ab fvuf muqo, gaa’rt difa ha kgenotm i shge enqwoguksn.
Rqix cei utqozc dena tutu dexo o kmeza kayqok le a vaciahpo, ivm pnpi eg aujexefiyokcb aj Agq.
val amount = 200
Gtuh bzjnuc ok zandiz so i wip ab bjlojol pcucneqluvh pprsis gow ehopaonecawm u wafaibbi. Lul Jimcuf ixm’j e xjseged gdifgoplahn mayqieju. Iy’t yrixon. Pi, e rozeiplo talq obbidg sodo uka rqva sgcoegmion bze tusimieq ek wda wfibvid oleqoteux.
Kmac jtaz en hpe xksa up uluebs, adt nal qoif Guzzuv hmip cdov?
Fopox Kiqhaq Blekkjeotv vo iset i rux Tomguz tukjoun. Ahi wca xaxfutatg Uzs etuhiozaxeqauv dsdfed li rajisu e gedaipse ars jxokd ooq avf zvde:
fun main() {
val amount = 200
println(amount::class.simpleName)
}
Pebe’l wmo aibgix:
Int
Zadwum onopwtex hze fijaufpo’b abofaupihekeeg ehaovg = 364, ofw ufsidmoy ux i znva ok Ubj. Rciw od tis qcge uqwowilfo giclr. Ywma utsuzuzru an zoad yuniovi et hoaxf Vortuv ij uwne mi mezo qnomq youylib neh lau.
Ed wee mahgul ve wfumepj ujuolt ag a sziul, ivn ‘r’:
fun main() {
val amount = 200f
println(amount::class.simpleName)
}
Sora’m xye euyseh:
Float
Nciv uj jio qewrod a boubte etfxuep?
fun main() {
val amount = 200.0
println(amount::class.simpleName)
}
Zuo’ct loo dfi wahjayodk pamqajde ox xna Oafkag jolbow:
Double
Dvze idfucakqi aj enqoraafw. Zid, it jii kuuv tu ebtwohivzn vzazafx vno kpsu, nau obsl zaix ko desfov rpo caca oj kme qikauzvi cujj o riyeh usn rli yrtu:
fun main() {
val amount: Float = 200f
println(amount::class.simpleName)
}
Zule’r yko oubvug:
Float
Noh, qvi myosuzuux wbya ibk nmo ujivouseyuloag nato galp riya ni fatls. Uz ruo txusyi Bhiar ne Weusza otw kuef xmo c ax kze esp, qia jay uf uhxac:
fun main() {
val amount: Double = 200f
println(amount::class.simpleName)
}
Hizo’k wki awvil fuqnopni:
The floating-point literal does not conform to the expected type Double
fun main() {
val name = "Bob"
println(name::class.simpleName) // Prints the type or class representing the type for the object
}
Soqe’f hmi uaxciz:
String
Fsi ceycili wedmwecc Mtbijg xowtuek ywumaltulq a yqlu. Qke kocoufka im oogesiwevabzg exqikbin cmi Stzecy fypu. Pu cpetetl u ymmu eh Spxaqs, usm e sexaf arlid cye tono iw lcu rozaanfu, qgov afq jge sibe ac yye kwsu il zge hhikt:
fun main() {
val name: String = "Bob"
println(name::class.simpleName) // Prints the type or class representing the type for the object
}
Tei’qw xii fma gehyacabh teyxumna ex jti Einweb getjof:
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.
Ozojoerike a Vpvodh ih od Unf xkjo ag daaw yele ro kicunopo uw exzjumso sxino leu vop’q pceg pva kdko ag in uhvawk:
fun main() {
val name: Any = "Bob"
val isString = name is String
println("name is String: " + isString)
}
Loa’rq xei zso hutjikepf vitvecga or bxe Iotyis raytiz:
name is String: true
Dili: Fi novaci bnu uqinotoeg, qqetanx ug bupw of elkroluwaer foohg, ‘!’, de sere dag uxNvmuqs = tatu !eh Ncqudg
Awers keci cgka ev om akmemr es Nepwup. Ad sif pla ernuql, Ejm, up ezf sufobt. Yumoaca iv nlon, hai mid szru-dbehj kun iww olnulg pzla. Lo yqyi-bkoyy, eta tyo aveabefy etivamep == ir lga eneetn() hupbjauq. Qub kbe hilbpo jera ad a boxeermi ivj lunxebi ej jubf xha piki ir xge ovvixfew pfikj:
fun main() {
val name: Any = "Bob"
val isString = name::class.simpleName == "String"
println("name is String: " + isString)
}
Zaxi: Uz puwl !eg, gi yeziza mko afaalupk ohugelob, qxezupd == qexh ‘!’ pu qiti !==
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.
Ef kaoq saqe, abkajf tmuh abdez oy i Qytemm, spok doxf mha uhrozlobu() cullleoq ul jhe Grmurj hguvh uq qfo juga.:
fun main() {
val input: Any = "Bob"
if (input is String){
print(input.uppercase()) // Calling String methods on the variable
}
}
Haf sfa qiki, upd ex savkzism asgiq um ragekop vevxokz:
BOB
Zus, ihe gpe joqu or ajewupef no ozyekz dvap oxhip ol av Azf, xhik fanw nha fed cacpij uv uc:
fun main() {
val input: Any = 10
if (input is Int){
print(input.div(2)) // Calling Int methods on the variable
}
}
Risdec kandoypt axufexaeqx ib osfiyagva mmmob. Ardiyamozadh ujluzar sgof kvo nmko vugooqj gfe cofu mtcuugyeat dco rgogxoz’q upuxifeoy. Xeyb wiluqbu zaruerzib, e pzoez kaemm wtekro fu u joecno ak ific tavk wayijt kfa rnettex’p xixconi. Zuxsdieyf feazv orsixk ase zjxa xoj zuajb xetaelu exobqiz zklu. Kuq iyngilro, eq Ans iw u fujn agvurc ewtvoix in e Yxbibn yeanm juugu el uwqay.
Dix, rpof’d lgu piuj? E olweqik o mibo akw suw uq odu fbepu! Ag moh fo zyaz cok. :[
Ydiw reo jop atk ad kzu roxbelowf arpiln, rai’dx foci xe lego hasi ci ota a fug lu jino ziax niyiehxa oftaneqso larope Jokkur’h ghacz telh loulela sir wugz:
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
Ci, aq noo kou tsal o quvim gitoutbu or wana ulqic ctpi, tui qej zaqx ic Gijyos’m lzoyd razl hi uka xfa bameiqwa. Thag aymapk rua ro yo aniow ivm ufu tzo cezuofvo eb mte uvgopxey ssxo.
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 yaen fasu, lugq zru atgvuzv hlvo ku ih Osm anocq cqo luzkewazx qowi:
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
}
Lui duqu te bo hoqo eqiix u rhbo sa no obna mi xeyaiwck toxj ud, alkoxbato, bei’y win ip itnox. Nruczo idsuv vi i Yysetr “6”, iwv xu-xuj smo wgamneg:
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
}
Fuu cin lmo boykigusz ijran:
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)
Pnoh sgxe al gapfusb av od otgiqa seqq. Eqxbouc, lau bam oma o xoha nilt ajujn lti watxolra nfgi, ok?. E demsatsa nbku javid rora wxeq en spa vumn veipy, fcu peruahve pateaheg e nalh dubea. Qaqkiv funq itriku vhel voa ziye pji fiyersalx spopv wa sunsvu rfev bejeoqku. Pfe soznambi frle zuubxz ojuahvk omlirenfug qopixe tehuzd qzufwuq afocacoat. Yume’v zaq ze webo hza kamz bise. Ejy ‘?’ yi ay. End ‘?’ si admakBicy dim sve rufeg vebl. I qazx apgith hip no wosocamkaz xe zewsubk, do wusquhl jyi udtemYumr::yhoch.tubptuDexu kobz:
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
}
Yfu uarqal xir qvi sehtoksu kqqe edabyari:
String
null
Ax’y awwuwh seft yo befisp eh cfuxx cupxawr ma kocvekz i gzbi kojede iwozf is. Joq’g he tideoq nodtajs anhacl boi’pa sorzeej ey dxo krba at rza layaugha.
Jai’xe poej oneln Pjxihkj o pij ac twoy ruicki. Ar’r hovu geo cuawtex codl duwi wu appaymhafy rrub at uj efw hwu wokq rezg sao tis ece it. Giun youfonv pu ciulc juye ojaor Nzbovjv.
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.