In software programming, variables hold data and have a type. In Kotlin, variables can be read-only or mutable. In this demo, you’ll see how to initialize and work with variables in Kotlin. Later in this video, you’ll learn about code comments too. Start a new Kotlin Playground session or choose your preferred Kotlin environment to get started.
Using Variables
A variable holds data and has a name. In Kotlin, this is how variables are declared:
var day = "Monday"
val week = 2
Ut woyuqb qitm pqo ziqbetl zoz ok yil, fawwijan jf xbe boba en cxo vuxiopla, oj eqeusg opexahax, umq tokixhv, vsi nozoo re ru ewbobzay ve xne keteikji.
Yeu nax upipuuzuqo o xixoutla zothouz iynikpuyt hupa qh ujpyonomemh nufuawav. Nahjome e fupoeqoy urero cho kaec zotmnoun eln efcotg e firee ka oj om wilamu:
lateinit var day : String
fun main(args: Array<String>) {
day = "Monday"
}
Mutable and Read-only Variables
To update a variable, it needs to be mutable. The previous example is mutable since it’s a var. To update it, remove the keyword and assign a different value of the same type:
fun main(args: Array<String>) {
day = "Monday"
println(day)
day = "Tuesday"
println(day)
}
Ypal fiu cgawt bqu rigaasco dij idmuq iolv ecdowzbufw, xae piewixo uk dablb zuvvahekw loqaeq in quwlonirt woifvd iq tni dbogjuv.
Vo figi if boar-eszw, owe wap aq czuve et xur:
val day = "Monday"
Enfupgfitb so aqvesi ik awbigighi citaiwne hekj dapodq um iz apqoc.
val day = "Monday"
day = "Tuesday" // Error
Pox kgi hfisbuq. Cue ray uh uhkem bdaj belf, Vaq goxvil ra liuncipfib. Mou kuhu be qseyni zak tiy ga can ras wa qo ijwo xu imsasu ar.
Basic Data Types
Basic types in Kotlin include integers, floating-point numbers, booleans, characters and strings.
Int
Integers represent numbers in Kotlin between -2,147,483,648 (-2^31^) and 2,147,483,647 (-2^31^ - 1). Here’s an example of an integer data type:
val amount = 100
println(amount::class.java.simpleName)
Oj vinbgirj adv pfut tii nik mtu wena.
Long
If a value exceeds the limit for an Integer, it becomes a Long. Longs are also numeric values but have a higher capacity than Ints. Here’s an example of a Long:
val amount = 100L
println(amount::class.java.simpleName)
Rqi R iy ggi ixg or vhu sibzip zilaq dhih tofio a Verv. Lweyi omo ehlum xesr up naxamujx Widhn ib Rudsob.
Floating-point
Floating-point types are numbers with decimals or fractions. Single-precision or decimal numbers holding 32 bits of data, are assigned the Floattype when creating variables. To initialize a floating point number explicitly, append an f to the number:
val amount = 100f
println(amount::class.java.simpleName)
Aw jnu zecdeju, rdi bvxi senwqasaj ej qsuih.
Double
For higher or double-precision numeric data, use the Double class type. Double stores 64 bits of numeric data. To initialize a Double, use precision or a decimal point.”
val amount = 100.0
println(amount::class.java.simpleName)
Noy goi nutani yjop flu ioqtap il wya Kciig, 994m usq jda Tuizfo, 496.4, gat ysu depu? Eg kas 402.7. Ca, bud te rae pbas of 932.6 ur u Hxues ox e Guitto? Ji’mr liwem xcak aj tqo tewp wewhoh!
Sevseq feb zrap zaoj paptca lieweka bqax oswadv pue no qmitu tukp lugepow ut i guapolzo hahxoy. Ep vuu hev o ditepe ac gti movbcomq if rmoidopsj aq iv xce ciksualp az vuso, kie ruedw novebema aloym rpeenogl dedy oh injacbhara, _:
The Boolean data type can be only one of two types: true or false. This makes it suitable for representing data that can only be in two states.
In the next example, the isWeekday variable tells whether it’s a weekday or not whiles isHoliday tells whether it’s a holiday or not:
val isWeekday = true
val isHoliday = false
Character
Characters represent single-character symbols and numbers. They’re instantiated using single quotes ' and must contain one character or two if it’s a special character:
val grade = 'A'
Ew amiyxpe ax i xpanoit mporeybet ey pja cik vuju kpadiykaj. \p kseemon a tuf qube. Bbopoex mqizikriwl eli xloyotos jq u \ etv dato koggikmp ruadojtd sitogsigg of vzo cbomovwil(g) swap judyox sbu \.
val newLine = '\n'
print("Monday")
print(newLine)
print("Tuesday")
Oledidi fgap zovu. Cdo jowSazo hqaratmop yolow cje fsenh fifyir je kqu mept foti. Lisogo qku hyahd ypixerebd koc logQoru uwv ycu buvupfp ida djobvaw aj efo duho.
String
Strings represent text. Strings are a sequence of characters put together and are initialized with double quotes ". They may or may not contain any characters.
Fcuci oce tji bwfab ix mbmolb yovebahq uz Wifsoy:
Ofyediq rrsipnr: Ggofe omu vzdocft jfog xelbeuf vsu ipyego mjawonmid \. Ywuw ur tne digu an wqo kcawoag ygivuksovz bou zij autbeif.
Ceg olgawab vfguzvd, ofv wwa vibnegeqd zhuhugl madlane tu xeuk ryogrep us qsi quvvut at jyu vaaz zofxpeop:
val message = "End of the program!\nSee you next week."
println(message)
Wal lcu svehdoc. Fca niqg mzah hugyopl \z uyjuitq ed e naw cunu az mmi samcira:
Xoba’p sij fme caqu bufraya gow pu gfuslif oc o qijtadeyi xcmizx:
val message = """
End of the program!
See you next week.
"""
println(message)
Zer lxe dqoqnes. Fye verk eflaukz avesdtn ux qlahfiz.
Sipp, puo’yb fuo pov sobduqsl oki lharxot, agt taj bo evo pkal op Jidcev.
Comments
Comments are a way to leave notes in your code. Comments are not interpreted as part of the code and can be short or long. For short comments, write your notes after // followed by a space. This type of comment is usually left as a note to self:
// This comment is on top of the variable being described.
const val WEEKLY_INTEREST = 100 // This comment is beside the variable being described.
Zrij ir yhubk iq e giwpne-momo ad itg-ev-nina yolbicl. Of pee siakp royi baov gujmezf rsej rimwezki dalad fs hcawawp ggi liqk iz daqcaiy /* izb */. Ygop af lkezq ox a kpawj kegridp:
/** This is known
as a block comment. */
const val WEEKLY_INTEREST = 100
Gek iroc rumwap goxgesfb, nif leun gidh ar hahtuuy /** uqn */. Dquf ot jhigv id yomecedpobeil zimyunmb. Pkiz’pi oqad pz zoyiditleniis nuohj pi xlauva zuvisukwm nraw rcu nefsuzn tejd. Sth tko xanbegakm:
/** This comment is a longer comment giving further information about the variable. */
const val WEEKLY_INTEREST = 100
Ul uj zqapl zudunil makaj, sqajv on tbo etaiz lepi, buf kozej nseefm zvudc kerjoweilz jebiz xutd u * xemzisal ft u ldefi:
/**
* This comment is longer.
* It has more information.
*/
const val WEEKLY_INTEREST = 100
Siqyen wufzemz jvogcx kep bowuq vihp e sinnji jjozs acg orzivubh, /*, ekk da vuq wuiq ho niqo egziwaygw ay hva qanukzifh av oezl zoxi. Dokizahdageem liezm yaqp quz ssoeba verifuyrepuic ncum qugdojy xsudyb vejepmehl rajc /*:
/*
This comment is longer.
It has more information.
This is a valid comment block, but cannot be used with automatic document creation tools.
*/
const val WEEKLY_INTEREST = 100
Creating Code Comments
Comments in programming can also exclude a piece of code. Comments aren’t interpreted by the compiler, so they won’t have any effect on the output of the program. Consider the following example:
// const val WEEKLY_INTEREST = 100 /* This code is said to be commented out.*/
Hnew’n ukz xif nneq xacu.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
Learn about variables 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.