1

I am new to Kotlin and I try to understand the shown short code for swapping the values of two variables. I don't understand why it and b have different values in the also function. Don't they reference the same memory address with decimal value 2?

Thank you.

var a = 1
var b = 2
println("a=$a b=$b") // a=1 b=2
a = b.also { 
     b = a
     println("it=$it b=$b") // it=2 b=1. Returns it
}
print("a=$a b=$b") // a=2 b=1
Michiel Leegwater
  • 1,172
  • 4
  • 11
  • 27
N00ne
  • 63
  • 1
  • 7
  • 4
    `Don't they reference the same memory address` - they don't. `it` contains a copy of a value of `b`. `also` is a function, and as such, it uses standard pass-by-value style. –  Sep 16 '19 at 14:17
  • @dyukha and if you try the following? Does this mean that Int is treated as primitive type in Kotlin? var original = mutableListOf(1, 2, 3) var altered = original.also { it.add(4) } println("altered = $altered") // altered = [1, 2, 3, 4] println("original = $original") // original = [1, 2, 3, 4] – N00ne Sep 16 '19 at 14:36
  • 1
    https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value –  Sep 16 '19 at 14:41

2 Answers2

3

In b.also { it -> b = a } it is effectively final. So, it will always points the same value.

Cililing
  • 4,303
  • 1
  • 17
  • 35
  • Based on the fact that Int is treated as a primitive type? Because when you pass for an argument, lets say an array, the changes you commit on it and on the caller object are the same. This means that they operate on the same memory address, right? – N00ne Sep 16 '19 at 14:40
  • 1
    `it` is `final`, not necessarily immutable. You cannot reassign it, but you can change its contents. – gpunto Sep 16 '19 at 17:03
1

The it variable is not an alias for b, it is a separate variable that has the value of b passed to it before the lambda is executed. You can think of it as Kotlin implicitly creating the it variable like this

a = b.also {
     val it = b // implicit
     b = a
     println("it=$it b=$b") // it=2 b=1. Returns it
}

This isn't what actually happens, but if you look at it this way, it might help you understand why re-assigning b does not affect the value of it.

Leo Aso
  • 11,898
  • 3
  • 25
  • 46
  • Based on the fact that Int is treated as primitive type, or pass-by-value, right? Because if you pass an object, let say an array, they reference the same object in memory (it and the object on which also is called). – N00ne Sep 19 '19 at 15:39