Kotlin Variables - mariamaged/Java-Android-Kotlin GitHub Wiki

Kotlin - Variables

Declaring Variables

Short comparison
  • Java developers are used to variables requiring only a name and a type:
int count;
  • Languages like JavaScript are weakly typed.
  • Where variables do not need a type declaration.
  • However, they might need a keyword to identify that the statement declares a variable, as they do in JavaScript.
var count;
  • Ruby does not require any keyword, but it does require an initializer to supply an initial value:
count = 4;
  • In Kotlin, the required items are:
    • A keyword (var or val).
    • The name.
    • In most cases, an initializer.
    • The type may or may not be required, depending on the initializer.

Typeless Declarations

  • If you are initializing the variable as part of declaring it , Kotlin will infer the type of the variable.
  • Here, Kotlin sees that our variable initialization code evaluates to an Int, and so it declares the variable count as being of type Int.
  • For example,
var count = 5;
println(count::class) // Prints class kotlin.Int

Typed Declaration

  • It is also possible to declare a variable with a type.
  • In this case, the type is unnecessary, as Kotlin can determine that we want an Int from the constant we are using to initialize the variable.
  • But, as we go deeper into Kotlin programming, there will be places where we need to specify the type.
var count: Int  = 5

println(count::class) // Prints class kotlin.Int

Declaring Read-Only Variables

  • A closely-related keyword to var is val.
  • It too can declare a variable.
  • Except that val variables are read only.
  • After you initialize them, they cannot be changed.
val count = 5;
println(count::class) // Prints kotlin.Int

val count: Int = 5;
println(count::class) // Prints kotlin.Int

val count = 5;
println(count) // Prints 5


// However
// This works.
var count = 5;
count = 7;
println(count)

// This does not.
val count = 5;
count = 7;
println(count);
  • You should get a syntax error, akin to:
error: val cannot be reassigned 
count = 7 
^

Prefer val over var

  • You will find that the vast majority of Kotlin code uses val.
  • If anything, var tends to be considered as a "workaround", for cases where val cannot be used for one reason or another.

More Operators

Now that we have variables, we have more operators that we can use.

Increments and Decrements

  • Akin to many other programming languages, we can use ++ and -- operators to increment and decrement a variable by 1.
  • Of course, these only work with var, as the value of val is "immutable" and cannot be changed.
var count = 5;
count++
println(count) // Prints 6.
var count = 5
++count
println(count) // Prints 6.
var count = 7
--count
println(count) // Prints 6.

Augmented Assignments

  • Similarly, there are also operators that evaluate a mathematical expression and assign it to the var in one shot, such as +=.
  • The are -=, *=, and /=, %= operators as well, combining those mathematical operators with assignments.
var count = 5;
count += 2; // Equivalent to count = count + 2;
println(count) / Prints 7.

Unary Operators

Most programming languages offer ! (or some equivalent) as a "unary operator", which inverts the value of a Boolean:

val isThisTrue = true;

println(!isThisTrue) // Prints false.

Kotlin also has a - unary operator, which negates a number:

val whySoNegative = -5;
println(-whySoNegative) // Prints 5.

No Automatic Number Conversions

  • In many programming languages, you can convert numbers between shorter representations (like a Java int) and longer representations (like a Java long) just via assignments.
  • The compiler knows how to "upsize" the value.
     
  • In Kotlin, though, that only works for literals, not variables.
// This works.
val thisIsLong: Long = 5;
// This does not work.
val thisIsInt  = 5;
val thisIsLong: Long = thisIsInt;

println(thisIsLong::class)
  • The compiler error will be something akin to:
error: type mismatch: inferred type is Int but Long was expected.
val thisIsLong: Long = thisIsInt;
  • Kotlin wants you to intentionally perform such conversions.
  • There is a toLong() function that does the trick.
val thisIsInt = 5;
val thisIsLong: Long = thisIsInt.toLong();

println(thisIsLong::class) // Prints Long.

String Interpolation

Many programming languages offer some form of "string interpolation", where strings can contain programming language expressions directly in them.

JavaScript Example
  • Using backticks to enclose the string.
let count = 5;
console.log(`The value of count is ${count}`);
  • Prints: The value of count is 5
Ruby Example
  • Ruby has a similar capability for double-quoted strings.
count = 5
puts "The value of count is #{count}"
Kotlin Example
  • For a simple variable reference, you can skip the braces and just use $:
val count = 5
println("The value of count is $count")
  • Arbitrary Kotlin expressions can be used with ${} syntax:
val count = 3
println("The value of count is not ${count + 2}")
  • This can be very handy for assembling a string from many pieces, compared to using something like StringBuilder in classic Java.

Hey, What About ?

if you read Kotlin code, you will see variables declared with questions for types:

var something: Boolean? = null;
println(something)
  • Kotlin has many features that are not seen very often in other programming languages.
  • One of the most important of these features is how Kotlin handles null values.
    • Boolean is a type that is either true or false.
    • Boolean? is a type that is either true, false, or null.