Setters and Getters in Scala Trait?

In Java, I sometimes defined an interface to ensure that classes had "setters" and "getters."

For example, if I have a node in a tree, I can define an interface, for example:

public interface Node { 

    Node getLeft();

    void setLeft(Node node);

    Node getRight();   

    void setRight(Node node);

    int getValue();
}

and then my nodes will implement this interface:

 public Node2D implements Node{
     //implements all of Node methods along with getters
     // and setters
 }

Would I do the same in Scala, or is it done differently?

+3
source share
2 answers

Getters and seters do not occur in Scala. In fact, var is internally implemented using two getter / setter methods. If you want a volatile solution (which is usually avoided in Scala, if possible), you can simply write

trait Node {
  var left:Node
  var right:Node
  var value:Int
}

class Node2D(var left:Node, var right:Node, var value:Int) extends Node

Node , vars , , , alltogether :

trait Node {
  def left:Node
  def right:Node
  def value:Int
}

class Node2D(var left:Node, var right:Node, var value:Int) extends Node

, Scala (, Node2D Node), , instanceof Java.

+7

Scala var s. , var :

trait A {
  var x: Int
}

var , :

class B extends A {
  var _x: Int = 0

  def x: Int = _x

  def x_=(value: Int) {
    println("Setting x to "+value)
    _x = value
  }
}

class C extends A {
  var x = 1
}

, , :

val b = new B
b.x // is 0
b.x = 10
b.x // is 10

val c = new C
c.x // is 1
c.x = 20
c.x // is 20

, Scala - . . http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-2.

+5

Source: https://habr.com/ru/post/1791711/


All Articles