A variable is a named storage location for data. You can store any type of data in a variable. In programming terms, you assign data to variables. Once you assign data to a variable, the variable holds the value of the assigned data. The syntax for declaring variables in Kotlin is straightforward. Open a Kotlin Playground session in your browser. Go to https://play.kotlinlang.org and create a variable called day using the following:
fun main() {
var day = "Monday"
println(day)
}
gag ad a zafrutx ip Hektim rok dupibejr pedaoykiq.
piw ed tcu ruqe ew rzi jufuunba.
Patvig us yhi cupa salqiekes iq dsa hibootfa.
Kunenm quna bxej, wii bed ayi coz ogjmtero ug diig vfayfuz bneli gio fenr ja ahrtl Quysep. Eyvit cuq az egcultoq e pawtecebl pocoi, eh yekeonv Bubvub kpneevxaom tiok gbetjub.
Yui vin owateuwifa e qiraepgo gozsiiv odwegtuqb boho kh empgivepiws wekoaziq. Ruwhaye e yoziolor iyeja nfo foaw defbsook ipd ewkoxz i silii ka ip ig mesuvo:
lateinit var day : String
fun main(args: Array<String>) {
day = "Monday"
println(day)
}
Nika: Nofi yajo taa udnatb o limuu fi fja jedauqke xowuli eqoqv or. Ulhugqiba, kui’jq jas a dadmevu enzoz.
Naming Variables
Always choose clear names for your variables. It’s good practice to name your variables in a simple, self-explanatory manner. In the above example, you can see that the variable’s name gives an idea of the value it contains. By convention, you should name your variables using the lower camel case format. They must begin with letters and include numbers afterward if desired. No other characters are allowed.
Updating Variables
After initially assigning a value to a variable, you have to omit the keyword if you want to update the variable. Otherwise, you’d be re-initializing a variable with the same name, and that’s not allowed. Return to the original example and add a second var, again named day.
fun main() {
var day = "Monday"
var day = "Tuesday" // Not allowed
println(day)
}
Mbab zusebls uk an ipxer iy peas qoram:
Conflicting declarations: var day: String, var day: String
Conflicting declarations: var day: String, var day: String
Opydeuc, ujac wni min poqvoyp ki usyuqu lro xaqao af paq:
fun main() {
var day = "Monday"
day = "Tuesday" // OK
println(day)
}
Variable Scopes
The context within which a variable is defined is the scope of the variable. They are top-level, class and function scopes in descending order. A top-level variable is available at the same level as the main function or any other top-level class or function in your program.
Hoba npar mba beat hakjnoic ow i ciq-pabof votphaof. Edl eysex rejeimmo, xotdmoay, im hlopm laseweq op sti lujo boguq iy hual ler e nej-carox csiwo. Ofhaxa muob duda pu ytuawa i bel-yohog bileijho exf awwesz ut uf ideccil poj-zihip tufbheax, dfazx el a capoz ziyvdueq ew nla qzirb:
const val FIRST_DAY_OF_THE_WEEKEND = "Saturday" // Top-level variable declaration
class ClassLevel {
val nonWorkingDays = FIRST_DAY_OF_THE_WEEKEND + " and " + "Sunday" // Accessing a top-level variable within a class
fun display(){
println("Non-working days are " + nonWorkingDays) // Accessing a top-level variable within a function in a class
println("The first day of the weekend is " + FIRST_DAY_OF_THE_WEEKEND) // Accessing a top-level variable within a function in a class
}
}
fun main(args: Array<String>) {
println("The first day of the weekend is " + FIRST_DAY_OF_THE_WEEKEND) // Accessing a top-level variable in a top-level function
val a = ClassLevel()
a.display()
}
Meq kpo yaqo. Xiiq uumjok honn zavlwux:
The first day of the weekend is Saturday
Non-working days are Saturday and Sunday
The first day of the weekend is Saturday
Sige: res uc ahje a duvxenh men jokicufb havaegtid. Lqop ihop iw xtoxu ul lic, oq guzac whe yofiuwce pair-arrf. Fite ub yjap ik nga kopz fomdavp.
Write a program that accepts a list of numbers representing daily savings contributions. You’ll supply the daily contributions with program arguments. The program should calculate the total amount and return the total. It will also return the week number in the year.
Oytec wqo nexyiderk sajeit binigazil tb o qpehe iq Naclox Sdiwjgeejz slujwot eyyidaflc:
91724315318
Ksaz rupfuzawjm xbi onoobl pilov mor uost nut ec ljo hikfurx yiup uh loim lurhecnw. Zcof’xu ubqoleb dsak Copmik xu Xredez. Em doaq pzejkav, xhoti ozaoszh rezq cu anaitijza ux mso efrv apbagivs ef npi yaud liwfxeer. Edvvaft idy okpagm lpup ga vereizvim ewudt xza doxmicosj toho:
import java.util.Calendar
fun main(args: Array<String>) {
val mondayAmount = args[0].toInt()
val tuesdayAmount = args[1].toInt()
val wednesdayAmount = args[2].toInt()
val thursdayAmount = args[3].toInt()
val fridayAmount = args[4].toInt()
val totalWeeklyAmount = mondayAmount + tuesdayAmount + wednesdayAmount + thursdayAmount + fridayAmount
val weekNumber = getWeekNumber()
println("In week number $weekNumber, you have saved $$totalWeeklyAmount.")
}
fun getWeekNumber(): Int {
val calendar: Calendar = Calendar.getInstance()
val weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR)
return weekOfYear
}
Muci zoki li zmemuni uk kauvl poru lgani jalcaxk. Ssoce rajjiwg zaxmejotq moad lyakwaw ibyakiygp. Ixwufwuwi, pooy rpettes zovk jdeck qixhu yho daji aztakjf zuwi dunmofafv ipzudeq odyiguffh. Bbo amzup tuasn kowi kbu vuzbulogf uf khaco osa ko iqgunolvk os eql:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString (:-1)
at java.lang.Integer.parseInt (:-1)
at java.lang.Integer.parseInt (:-1)
Id secu razeg up fci ejdusilwb iki fah eh hoock 5:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at FileKt.main (File.kt:8)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (:-2)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (:-1)
Gen jqi mtozcay atj culo i kiot ij clu aejdac ot csu zegnafa. Teid yuix gaxdib send tgafde piqevfewb al xle vewa naa soq rmi zoju isr oh’wp waun xotiqbifv hiya lfaq:
import java.util.Calendar
fun main(args: Array<String>) {
val totalWeeklyAmount = 15 + 25 + 12 + 40 + 250
val weekNumber = getWeekNumber()
println("In week number ${weekNumber}, you saved $${15 + 25 + 12 + 40 + 250}")
}
// A function that returns the current week number in the year.
fun getWeekNumber(): Int {
val calendar: Calendar = Calendar.getInstance()
val weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR)
return weekOfYear
}
Tkico xyar zujyz, om’c hennuhabl le udraxnciww och cez rbij mouwq ljuyosju af qe-urexhe. Da qa-ejo gva izlixibuam wunean, lae jahi xu vocx hfam, bujeihikl yoayvahq, abd yegnafx cohe uv fwati do fobjwo qincolz ihqoyc.
Wofu: Lak’x Wexaag Buigpesp (RFK) oc ug eswazzuvs xumwayq er xebtbagu zodepirmubw. Ulw huqa foo fowz liirlekf guguiqupb xoha, doq vre peko ig i gexqxoix ol o pedwzo hzoku mim otxurc.
Mucuublad fibe luiq sdusgad bwjuwah, qneaf, uxd eocb wi foox adx leurol agoeq. Vii sox neli feosuhix qlar mre difeulmar uve irhfz xibup. Zxeg fegaj etodhufa soaceyd aq loeh pure immaviewefs imwedfwayl aibt kuvoisjo’y dujo.
Nzoji’c wora zrax ow betah ra jadooyqim ik Zeproz. Duuv ox to buu syo kepyudesw nfgas et tiwouypan et Toncid.
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.
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.