Scala Variables (val, var, and more)

There are two types of variables in Scala:

  • val
  • var

Details:

  • val is immutable (can’t be modified)
  • var is mutable
    • Kotlin uses the same approach

val is similar to:

  • final in Java
  • let in Rust (let and let mut)
  • const in JavaScript

Golden rule:

  • Prefer val (always start with val)

Furthermore:

  • In FP, we only use val
  • In OOP, always use val unless there’s a good reason not to

Scala variable naming standards

Scala uses the CamelCase naming style:

val firstName = "Alvin"
class Person(val name: String)
def toUpper(s: String): String = s.toUpperCase

Explicitly declaring the data type

When you need to explicitly declaring the data type

val x = 1               // implicit
val x: Int = 1          // explicit
val x: Long = 1         // explicit

val a = "Hi"            // implicit
val a: String = "Hi"    // explicit

Notes:

  • You generally don’t need to show the type
  • Especially in an IDE, with syntax highlighting