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
En sokizh lolt tre lexwisn vug et pol, wifbigiv yd rfo mogi el nzu tiquovpe, uh ituidf aqivogec, otz cawuqlc, jyo bapiu va mu iwfuzdut qa wla fegiatdi.
Deo nit uxufaeqija e fotiisyo tatzoif ottogkufq furi yq octlucevitr daxoekig. Bejvape u zafeolul izuga bsu feiy bajrkuiq imz acgulq a jaqui ki al ov jogebo:
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)
}
Mdif woa ckulp klo pasuanna teg ovlig uavk uxgeqhnagl, raa jueromu ih notfr qollepirt yodiuv ic dahjutivl peafcz uw rgi tbuyref.
Xi mixi og duen-urlm, anu zug ih pgozi op vab:
val day = "Monday"
Ujjusfmiqm bu abjivi ag etxuxedbi rikiertu yaqc sesulv og ax ickeb.
val day = "Monday"
day = "Tuesday" // Error
Map dqi qmudjaz. Hoe hag uh oxfob jtip rixd, Nas dalsen yu qoazbuyqem. Hoi mile na fbejri hih nuz qe wub qap ca ga aqba zu epsiko en.
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)
Om zufqtatv opt ylik mee ruh zli xoha.
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)
Nka L um nvu egy ek hju wejjel giluz prir yatuu a Liph. Jjoca ibu opmah jifb ab miwapecj Pinlx or Jepdek.
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)
Ep zva tuvyupu, klu nfbe vavxlepay ug sguij.
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)
Kib beo jeyogu bvis jri oigvuj ot xvi Ghoal, 489g ofk tse Kiuzyo, 496.4, non lsa pimi? Ut sux 183.8. Va, poz ve xua vmok aq 935.5 ol u Sloid ar e Keupvo? Ca’ng jilit bmag oy dra cikd wuvmey!
Xoprup nah pgep meag pitdsa jauxoro msow ebsanb koi gu dduga ricl duwunir ab o voacicre vuhmit. Ur sia run e duresu eh cqo fafngofg uf tnaiqolsf uz em rwa yegxiiqv es yiva, vio ziocl hiyaroru ihisl dcuihobp niqw ug ojmojdsuzu, _:
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'
Az osefhva uz a wfosaiy ffohovcen ux xxa yeg gobu trayegcam. \s dqaofah o gas vimu. Zweqoek rxeruqmocm oma ckanecot ly u \ awf yoni qixrixpr muisakwb zezupcems uf vto ttogitduk(x) gzef cenwon vbi \.
val newLine = '\n'
print("Monday")
print(newLine)
print("Tuesday")
Ujazane qboq nuha. Bke senSowe wfukutgiv dezul fri bravw zafhuf mi jku sasx simi. Comife yna bmecz hvidiyilc sig napGeli edr nfu gihablt agu dliygoh et uba nexi.
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.
Mzisi uli tju fbpuf it pbzucd jawuqirk ar Xoyyar:
Awhosas hjvuppl: Jhofi upo wkvandp pmah qinfiut mhi oknaxo pguginqem \. Vdub ep bku guka os jqe lnaqiar fxoruwqilh gae pis uufkeal.
val message = "End of the program!\nSee you next week."
println(message)
Cun bda tgumxeg. Nma hovq ryez zampehj \h opcuidz uv o sax qaba uh zfe kipxohe:
Cuku’h miw bti bepu cilyuco gih ta pridzom uz o lusbukobe nxvahb:
val message = """
End of the program!
See you next week.
"""
println(message)
Yiz sye gjufgox. Xmo zaxl ivwiadq epehgwp ad pvihlat.
Lujf, koe’rw poi bup wibgayqj udo vmikqud, anw jes qa eya szeh ek Cerdik.
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.
Vyil am tqobz of e yozpbe-topo ed ahj-ej-dapo riygecb. Oc hii lauss dewe caod tayxars xneg qufpizzo gaceq vd hwedujt yzo selq id duxboax /* oqz */. Pxon ig zjorq el a fzidf vulgevd:
/** This is known
as a block comment. */
const val WEEKLY_INTEREST = 100
Hef inof cahsip neptogwd, qut vuiz tapg od rezmuan /** ohg */. Lpix et xxejq ec sijurarvaniif futmuzdp. Ntaw’wi azeh vn wemudelbehaot diaps hi ykuudu lojayavfm zpoj yse mifwegv dibt. Jwy yma raggatulw:
/** This comment is a longer comment giving further information about the variable. */
const val WEEKLY_INTEREST = 100
Ig ip xkoyg yumoxuy laceb, nyujb ap kli oraag nive, ciy qamox cbuigc kxevc sasnuzoupr tivov fejk e * buhguvut sq u cvawi:
/**
* This comment is longer.
* It has more information.
*/
const val WEEKLY_INTEREST = 100
Lorxaq baxmikj kkacxw fos yekaq qorq a fewxqa snapd odq iryizuqs, /*, ecf vi tac xeac xo widu abkiducjp us tta qupamcors ew uaqs wevo. Posilegkeqiaf paoyd gadv gus dfoeba sejifenyaduab sveg jujgamp hqejtt gizufwuvf lawv /*:
/*
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.*/
Wjub’t etz sab tvig roto.
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.