title: Kotlin function parameter: Val cannot be reassigned
body: <p>I have written Red–black tree in Kotlin. Fun <em>insertFixup</em> restores balance after inserting new element (<em>z: Node?</em> is new element). Algorithm of tree balancing is taken from <a href="http://software.ucv.ro/~mburicea/lab8ASD.pdf" rel="noreferrer">here</a> (pages 2-3). The <strong>problem</strong> is that Kotlin <strong>does not allow me to reassign</strong> <em>z</em> to <em>z.parent</em> and <em>z.parent.parent</em>. I want <em>z</em> to be a <strong>pointer</strong>. The question is how to make Kotlin understand what I want from him?</p>
  
  <pre><code>class Node(key: Int) {...}
  
  class BinarySearchTree {
      var root: Node? = null
  
      fun insert(newNode: Node) {...}
  
      fun RotateLeft(x: Node?) {...}
  
      fun RotateRight(x: Node?) {...}
  
      fun insertFixup(z: Node?) {
          var y: Node?
          while (z?.parent?.color == "RED") {
              if (z?.parent == z?.parent?.parent?.left) {
                  y = z?.parent?.parent?.right
                  if (y?.color == "RED") {
                      z?.parent?.color = "BLACK"
                      y?.color = "BLACK"
                      z?.parent?.parent?.color = "RED"
                      z = z?.parent?.parent
                  }
                  if (z == z?.parent?.right) {
                      z = z?.parent
                      RotateLeft(z)
                      z?.parent?.color = "BLACK"
                      z?.parent?.parent?.color = "RED"
                      RotateRight(z?.parent?.parent)
                  }
              } else {
                  y = z?.parent?.parent?.left
                  if (y?.color == "RED") {
                      z?.parent?.color = "BLACK"
                      y?.color = "BLACK"
                      z?.parent?.parent?.color = "RED"
                      z = z?.parent?.parent
                  }
                  if (z != z?.parent?.left) {
                      z = z?.parent
                      RotateLeft(z)
                      z?.parent?.color = "BLACK"
                      z?.parent?.parent?.color = "RED"
                      RotateRight(z?.parent?.parent)
                  }
              }
          }
          root?.color = "BLACK"
      }
  }
  
  fun main(args: Array&lt;String&gt;) {
      val bst = BinarySearchTree()
  
      while (true) {
          var newNode = Node(readLine()!!.toInt())
          bst.insert(newNode)
          bst.insertFixup(newNode)
      }
  }
  </code></pre>
  
  <p><strong>UPD:</strong> Thanks to all! All the answers were helpful and I have found the solution in your replies.</p>