Scala构造函数混淆-请澄清 [英] Scala Constructor Confusion - please clarify

查看:99
本文介绍了Scala构造函数混淆-请澄清的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Scala构造函数感到非常困惑。例如,我有以下用类表示树的类,这些类的操作符为数字,例如Add和树上的叶节点。

I am very confused by Scala Constructors. For example, I have the following classes that represent a tree with operators such as Add and leaf nodes on the tree that 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)
    }
}

我读了在一个站点中,Scala构造函数中的内容会自动不可变(val),但是Stack Overflow上的这个家伙说除非您说的是构造函数的输入参数,否则它们不是val。 所以这是一个矛盾n。

I read in one site that what goes in a Scala constructor is automatically immutable (val), but this guy on Stack Overflow said "The input parameters for the constructor are not vals unless you say they are." So that's one contradiction.

此外,由于某种原因,我显然可能需要也可能不需要在构造函数中添加 val和 override?我的意思是我希望所有内容都是公共的且不可变的,并且要让Add具有等于 +的符号,等于加法函数的binaryOp以及两个数字a和b。有人可以解释一下如何使构造函数以非详细的方式在Scala中正常工作吗?

Also, I apparently may or may not need to add "val" and "override" into the constructors for some reason? I mean I want everything to be public and immutable and for Add to have a symbol equal to "+", a binaryOp equal to the addition function, and also two numbers a and b. Can someone please explain how to get the constructors to work as expected in Scala in a non-verbose way?

我希望能够执行以下操作:

I want to be able to do something like this:

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


推荐答案

Scala类的构造函数的每个参数在构造类之后都会被丢弃,除非该类的方法使用了它。在这种情况下,它被设置为 private [this] val

You are almost there: Every argument to the constructor of a Scala class is thrown away after construction of the class, unless a method of the class uses it. In this case, it is made a private[this] val.

但是,您只需添加 val / var 关键字位于构造函数参数的前面,它将被设置为公共 val / var

However, you can simply add the val/var keyword in front of your constructor parameter and it will be made a public 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 the fields from outside the class:

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

这篇关于Scala构造函数混淆-请澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆