使用类参数分配字段值 [英] Using class parameters to assign field value
本文介绍了使用类参数分配字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是scala的新手,想使用类参数将值分配给相同的字段。在Java中,我们在构造函数中执行类似的操作:
I'm new to scala and would like to use class parameters to assign the value to a field of the same. In Java, we do similar thing within a constructor:
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的事情吗?
Can we do something similar to what we can in do in Java?
推荐答案
Scala提供了创建此类成员的较短语法-只需添加关键字 val
在类参数列表中的参数名称之前。您还可以添加修饰符(例如 private
):
Scala provides a shorter syntax for creating such a member - just add the keyword val
before the argument name in the class parameter list. You can also add a modifier (e.g. 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
这篇关于使用类参数分配字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文