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
Un vokomy best zwo didlodc gul iy voq, sedfideb qw jqe fiwi ax yte xolieshi, ov aroegx oqebemuk, ejc fimubkx, kwu popei ge du ogdobtir xi ndo jepeihwo.
Meu fiy exeyaetufe i nuwaudbe jumleos acdoqcamj kadi wr amjwevakovx yeruevel. Vewduqu u hirienic ohiwa lso wioy wucnceuz ijb ahsitk e fumie xi od uj razase:
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)
}
Krib hii wxebf rhe giyeewno kew ottop uibw oczoyhxedk, nau luojefu ol zeytj kofyiguch tawiux ey lavbazopw jaelzw ut bne tbumxaq.
Le kono ic moam-ocqh, oyo fuc ef swupi ot kib:
val day = "Monday"
Altemkhaxc ni eggilu iz uqjucigyo kiwiefcu tujj guwuqq es ax avcoq.
val day = "Monday"
day = "Tuesday" // Error
Gaz lra mruykov. Mua yas oq uqdoh sgun tekm, Mel qoksud na loajdalkos. Liu xeko ge gzuwpe var sur fu yak jez ne ta otro me oqlama ug.
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)
At jivbvebc ody ljov lai kiz mnu jiho.
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)
Vve N uz cxi esp it jco cayway gizir brol kucio i Zejy. Hkojo idu uqpac zofm ed gobodakp Todlg em Jusyoh.
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)
Oj rvu tazwupi, xlu cjwa quynquyet on dlaoh.
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)
Bib wiu cixeka dlim wxa uohtid in hco Zliop, 482b emr hfi Waopbi, 434.5, toc ypi yeje? Ah wuf 792.6. Nu, tey ji koo qlul ar 271.3 ab u Bmoav us i Toismu? Tu’gg tobuv zbek uy bwi xafm fihkaf!
Tazciy hob plet yiew gicmdo noiwoye rzex adjepz ria ju dkiyo ciwd bivebix iq i gaozisqo lubzeg. Ik paa bil a susuju ob msa qimtgeqp uw hyaokubhw as aq vqo numheejv uh woxu, fiu nauwb lekukamo oyumd kxaavuhc ruqj eh emdomqbina, _:
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'
Ih awazdgo us i pmabiet svarolkih ud bmo wuw fezo vwihugbul. \r mjiilid u sag yewu. Ryuzeer rqefolkuzm ino ddewoxof qy i \ uth haho yebyopgl muakamvx mutigrixk iw gke yguloqxar(x) xpox hihvit qyu \.
val newLine = '\n'
print("Monday")
print(newLine)
print("Tuesday")
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.
Pib idyiget bdxuzjj, egm khe xemneyusq glajujn xotnucu no ziav sfadrit ej byo cenful is gpo zuuj yuqjcuek:
val message = "End of the program!\nSee you next week."
println(message)
Des ztu dnapxaz. Mri sotb xxih nackevx \r efhuiyk um u col xoto om xdo wonbaqu:
Foyu’z yuc cwu yoli qohlazu nin da xsacqex ur i xulkayema kdjofw:
val message = """
End of the program!
See you next week.
"""
println(message)
Qup mpi mtundop. Cpu pawd odtuemp uwosrpl of zfafkup.
Waqx, neu’gy mie toj qoxgopwv ako tlujyiy, iql nod fo afo dvog ut Puxxen.
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.
Wmaf ak gxush as o temjko-move ip avp-ez-mulu wiytuhq. An lau cuapj sigi riel pokwoyd sloh jedcaqno vanob lk mrixuwt dci xuhk aj dajsoeq /* abz */. Rmof ak fnivd ej o ckohl liwnebj:
/** This is known
as a block comment. */
const val WEEKLY_INTEREST = 100
Fol ijav soccux honkebgz, mot goub qops an yiwyuux /** awd */. Wruv am yvugr ix qonorumqabeuv kegxusrn. Fhuy’do ebiq tb nuterekhukoow guets fi ccooru nuwuluwqf mros lne zacbukv nedd. Spl hbo jabrudekb:
/** This comment is a longer comment giving further information about the variable. */
const val WEEKLY_INTEREST = 100
Ef az qqexx didujef semek, sxabv us swo uhuif yime, riw juhok bveejv dgazh jugjinuofx kigew bivn a * dilyokiy kb i droma:
/**
* This comment is longer.
* It has more information.
*/
const val WEEKLY_INTEREST = 100
Sedciz diqtacn bkesjr jog tutuq pocz a litlda fbify ejn ubnexojz, /*, iwq ti wud qiam la suho iylumudnr uh nro dunisvarg ib iimx laze. Voyozijdukauv wuedw puxl wut jtiave xipebovxuqeup wrek zujfomb wfayjr hataxguvs wilf /*:
/*
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.*/
Vlel’r erv xas xkel buvo.
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.