Values and Variables in Kotlin

What is a variable?

A variable is a storage for a value, which can be a string, a number, or something else. Every variable has a name (or an identifier) to distinguish it from other variables. You can access a value by the name of the variable.

Declaring variables

  • Kotlin provides two keywords
    • val (for value) declares an immutable variable (just a named value or a constant), which cannot be changed after is has been initialized.
    • var (for variable) declares a mutable variable, which can be changed (as many times as needed)
  • Both val and var keywords provide you a variable!
  • To assign a certain value to a variable, we should use the assignment operator =
  • It is also possible to declare and initialize a variable with the value of another variable.

Storing different types of values

  • There is one restriction for mutable variables (the ones declared with the keyword var), though. When reassigning their values, you can only use new values of the same type as the initial one.
  • For implementation click

Do's and Don'ts

  • The name of a variable cannot start with a digit.
  • Names are case-sensitive: language is not the same as Language.


Comments