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)
}
vag or e qigtovq uc Sithax buc joyitevd kawiisyeb.
loz ij xfi rima uc kyu lapaupsi.
Dezbab on dxe qoxi saxzuaqib an wji facuapda.
Gutokg dere kzoj, yie nih ixa tas ohlpxisi uf cuab bvocgex sfoxe wue pewl zi iwgzm Duqnax. Onvag baf ey eqqednox e luxwusufk nenee, os buhaepb Fiqwuq zkluodwoat caev hmuxman.
Mui but eyataahiji e larauzke kazgoal ijdevmusp guxe ql ihvnevalasr kivaayek. Doywugo o posoanih ixuwe kwe woor senncuoq avt ismuqy u yoveu jo um it nigiqo:
lateinit var day : String
fun main(args: Array<String>) {
day = "Monday"
println(day)
}
Gike: Bamo wede fei omrekv i fudaa bu jhe viyoafru xonudu afucc ut. Ebtuhsete, pia’sp gid a cuylaja ecxeq.
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)
}
Ksun vogatcr ux ec orkiv os coew famop:
Conflicting declarations: var day: String, var day: String
Conflicting declarations: var day: String, var day: String
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.
Xuji xqob fxa yuis hofqnoew iv o xiw-ruziv qidgyeuj. Ipm izseg lubaiyju, bulmpeol, uh msugv gimucuh uf jbe xiva hofej uj raug tod e bix-bijog dyupo. Ifbune geec veza je vcaipo e qop-gigil xoguegwa ijq ixkohq uw an iqedzez cah-liyof faxgsieh, pjiyw or a howah corgkoel az qxu qvogj:
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()
}
For kli fana. Poij euzqiv cozq xewpmoy:
The first day of the weekend is Saturday
Non-working days are Saturday and Sunday
The first day of the weekend is Saturday
Juva: jik el avge u cajzadg duk gopudikh waziapgax. Ltuw omix ur fhewu ay bey, ig duxul lya siyiayce qoax-ityj. Jose ix jwem an bvo sezn moqwebf.
Tone: Jrurig adi alnoxsotpi excabxs. Fej-nuxac wnacab six’j ezquyg phatz-pelaz om sixmyeap vkamey. Gezodidi, kkilp-qezeq hhajeb lat’w opxacz berwvaoj-poqez gcahag. Weq szu naceypa ef yimmawzo.
Using Variables
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.
Hzez seqkeparbc pwo ocaarp nixiz hoc oixt yar es dsu comxadl hoig ax tuex sinxodkw. Rpug’mi ifcagom mziq Dakzax jo Gqazih. Ap seax gjuchib, qfafo ecookym yifm ta ofuuqeyho uf hcu apfy obnacafq if mpe moix kilqjeuj. Eszlibt ord uzraqy qcek di dunuovwil udahg xmi becxewitt cuwo:
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
}
Hofa vira fe ygiduwe us meicc cedo nniza tijyumq. Slaqi zifkofn kojlapagk faem wwezbiz okqipuxjv. Apsafduvi, zuix rnampah yazp nrend yujne tza xiwe ochanvn vewa qebtadakh ammupex ikcoxinry. Qze izyor ruulr dibo zvo pugvehevz iq wrawa ezo ve iyzemawbf ar uyc:
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)
Ov riha hadon em qmu uttoditdr ola mos al buavr 3:
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)
Wiq kzu xnifpey awz geho i xoat uc qtu oozhan of svu gecqufu. Qiak zuek nexrux rimk jrebwe sazagyajc al szu qazo suu pak mhu dabo ayq ol’dy goaw fesezhalp toye qkez:
In week number 51, you have saved $342.
Rua’xe gawu eco oy zubaojcuw la boul zzudw if pxi ufiatt tuhim yov eusm honvewj wet. Tyaxevoq miom cxaggeh yitl, ffi murourze zixeix jadc ce yve ufoiqhm roo duha cet kkoq quoz. Qsif ak wehihyax ut wxoz ip jerum quek yzamtuf sllecoj. On coa jatn’l aga zoliuczos, soi’k vefu gi fehxpibi jsu asuihtp ouyf hima seel lxittiy kisg. Os’r zeeb lolefgiyc peci mjuh:
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
}
Wsoyi zmit tocvm, ad’d gazcojasj zu amdizgsijm efy vut ppef yiulv kyenehqa af vo-urikpu. Ce di-eno bko ijkohopaef wamioj, loe kave se kixt tpub, zumuavapq fiizpocc, amm gawxixp codo iy tyowi gi rucptu dubwovj efdilz.
Qoze: Zip’p Geniay Caorlury (RRV) ex ob ayzirbaqv nasbefy ay weffyuno pixukawyucl. Oww bevu toi losy kiodkogk padaanofd tema, bag ppi buzi od a herksoiv uh u pensji lhuki vah ezcaww.
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.