相关疑难解决方法(0)

scala构造函数参数默认为private val吗?

我已经试了:

class Foo(bar: Int)
Run Code Online (Sandbox Code Playgroud)

VS:

class Foo(private val bar: Int)
Run Code Online (Sandbox Code Playgroud)

而且他们似乎表现得一样,虽然我找不到任何地方说(bar: Int)扩大到(private val bar: Int)所以我的问题是,这些相同/相似吗?

在旁注中,我一直在尝试使用-Xprint:typer这些代码片段,除了第二行中的额外行之外,它们产生相同的代码.我该如何阅读额外的行?

..
class Foo extends scala.AnyRef {
  <paramaccessor> private[this] val bar: Int = _;
  def <init>(bar: Int): this.Foo = {
    Foo.super.<init>();
    ()
  }
}
..


..
class Foo extends scala.AnyRef {
  <paramaccessor> private[this] val bar: Int = _;
  <stable> <accessor> <paramaccessor> private def bar: Int = Foo.this.bar;
  def <init>(bar: Int): this.Foo = {
    Foo.super.<init>();
    ()
  }
}
..
Run Code Online (Sandbox Code Playgroud)

scala scala-primary-constructor

119
推荐指数
2
解决办法
3万
查看次数

scala类构造函数参数

有什么区别:

class Person(name: String, age: Int) {
  def say = "My name is " + name + ", age " + age
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

  age = happyBirthday(5)

  def happyBirthday(n: Int) {
    println("happy " + n + " birthday")
    n
  }
}
Run Code Online (Sandbox Code Playgroud)

constructor scope scala immutability

46
推荐指数
3
解决办法
3万
查看次数

消除与超类的类字段同名的构造函数参数的歧义

在玩 Scala 时,我有这样的代码:

class Superclass(var i : Int){}

class Subclass(i : Int) extends Superclass(0) {
   print(i)
}
Run Code Online (Sandbox Code Playgroud)

我发现print(i)打印出的构造函数参数iSubclass(i : Int)

现在,我的问题是:在这样的情况下,我怎么进入该领域iSuperclass

scala

3
推荐指数
1
解决办法
146
查看次数