Scala Constructor Conflict - Please Specify

I am very confused by the designers of Scala. For example, I have the following classes that represent a tree with operators such as Add and leaf node on the tree, which are numbers.

abstract class Node(symbol: String) {} abstract class Operator(symbol: String, binaryOp: (Double, Double) => Double ) extends Node(symbol) { } class Add(a: Number, b: Number) extends Operator("+", (a: Double, b: Double) => a+b ) { } class Number(symbol: String) extends Node(symbol) { val value = symbol.toDouble def this(num: Double) { this(num.toString) } } 

I read on one site that what goes into the Scala constructor is automatically invariable (val), but this guy in Qaru said, "The input parameters to the constructor are not vals unless you say they are." So this is one contradiction.

In addition, for some reason, I probably may or may not need to add "val" and "override" in the constructors? I mean that I want everything to be public and immutable, and for Add - to have a character equal to "+", a binary code equal to the addition function, and also two numbers a and b. Can someone explain how to make constructors work as expected in Scala not verbally?

I want to do something like this:

 addition = Add(Number(1), Number(2)) addition.binaryOp(addition.a.value, addition.b.value) 
+5
source share
1 answer

You are almost there: every argument to the constructor of the Scala class is discarded after the class is built, unless the class method uses it. In this case, private[this] val is executed.

However, you can simply add the val / var keyword in front of the constructor parameter and make it public to val / var :

 abstract class Node(val symbol: String) {} 

Usually this is not repeated in the constructor for subclasses if the field is already defined in the superclass:

 abstract class Operator(symbol: String, // no val here, only pass to super class val binaryOp: (Double, Double) => Double) extends Node(symbol) { } class Add(val a: Number, val b: Number) extends Operator("+", (a: Double, b: Double) => a+b ) { } 

Now you can access fields outside the class:

 addition = Add(Number(1), Number(2)) addition.binaryOp(addition.a.value, addition.b.value) 
+6
source

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


All Articles