我是 scala 新手,想使用类参数将值分配给相同的字段。在 Java 中,我们在构造函数中做类似的事情:
public class Test{
private final int value;
public Test(int value){
this.value = value;
}
}
现在,我尝试在 Scala 中做类似的事情:
class Test(value: Int){
val value = ..WHAT..value //Is there a way to assign a parameter value to a field with the same name?
}
object Test{
def testMethod = //access value and do something with it.
}
我们可以做一些类似于 Java 中的事情吗?
最佳答案
Scala 提供了一种更短的语法来创建此类成员 - 只需在类参数列表中的参数名称之前添加关键字 val
即可。您还可以添加修饰符(例如 private
):
scala> :paste
// Entering paste mode (ctrl-D to finish)
class Test(private val value: Int)
object Test {
def testMethod(t: Test) = t.value
}
// Exiting paste mode, now interpreting.
defined class Test
defined module Test
scala> Test.testMethod(new Test(5))
res1: Int = 5
关于java - 使用类参数来分配字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39095679/