scala 类构造函数参数 [英] scala class constructor parameters

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

问题描述

有什么区别:

class Person(name: String, age: Int) {
  def say = "My name is " + name + ", age " + age
}

class Person(val name: String, val age: Int) { 
  def say = "My name is " + name + ", age " + age
}

我可以将参数声明为 vars,然后再更改它们的值吗?例如,

Can I declare parameters as vars, and change their values later? For instance,

class Person(var name: String, var age: Int) {

  age = happyBirthday(5)

  def happyBirthday(n: Int) {
    println("happy " + n + " birthday")
    n
  }
}

推荐答案

第一部分的答案是范围:

For the first part the answer is scope:

scala> class Person(name: String, age: Int) {
     |   def say = "My name is " + name + ", age " + age
     | }

scala> val x = new Person("Hitman", 40)

scala> x.name
<console>:10: error: value name is not a member of Person
              x.name

如果您使用 valvar 作为参数前缀,它们将从类外部可见,否则,它们将是私有的,如您在上面的代码中所见.

If you prefix parameters with val, var they will be visible from outside of class, otherwise, they will be private, as you can see in code above.

是的,您可以像往常一样更改 var 的值.

And yes, you can change value of the var, just like usually.

这篇关于scala 类构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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