concept val in category kotlin

appears as: val, val
The Joy of Kotlin

This is an excerpt from Manning's book The Joy of Kotlin.

  • The val keyword comes first and means that the name reference is immutable (corresponding to final in Java).
  • fun sumOfPrimes(limit: Int): Long {
    
        val seq: Sequence<Long> = sequenceOf(2L) +
                generateSequence(3L, {
                    it + 2
                }).takeWhile{
                    it < limit
                }
    
        fun isPrime(n: Long): Boolean =
                seq.takeWhile {
                    it * it <= n
                }.all {
                    n % it != 0L
                }
    
        return seq.filter(::isPrime).sum()
    }
    Kotlin in Action

    This is an excerpt from Manning's book Kotlin in Action.

  • val (from value)—Immutable reference. A variable declared with val can’t be reassigned after it’s initialized. It corresponds to a final variable in Java.
  • By default, you should strive to declare all variables in Kotlin with the val keyword. Change it to var only if necessary. Using immutable references, immutable objects, and functions without side effects makes your code closer to the functional style. We touched briefly on its advantages in chapter 1, and we’ll return to this topic in chapter 5.

    A val variable must be initialized exactly once during the execution of the block where it’s defined. But you can initialize it with different values depending on some condition, if the compiler can ensure that only one of the initialization statements will be executed:

    val message: String
    if (canPerformOperation()) {
        message = "Success"
        // ... perform the operation
    }
    else {
        message = "Failed"
    }

    Note that, even though a val reference is itself immutable and can’t be changed, the object that it points to may be mutable. For example, this code is perfectly valid: