Scala构造函数参数默认为private val吗? [英] Do scala constructor parameters default to private val?

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

问题描述

我一直在尝试:

class Foo(bar: Int)

vs:

class Foo(private val bar: Int)

,它们的行为似乎相同,尽管我找不到任何地方说(bar: Int)扩展为(private val bar: Int),所以我的问题是,这些是 相同/相似?

and they seem to behave the same although I couldn't find anywhere saying that (bar: Int) expands to (private val bar: Int) so my question is, are these identical/similar?

另一方面,我一直在尝试在这些代码段上使用-Xprint:typer,它们 产生相同的代码,只是第二行多了一行.我如何能 读多余的一行吗?

On a side note, I have been trying to use -Xprint:typer on these code pieces and they produce the same code except for an extra line in the second one. How do I read that extra line?

..
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>();
    ()
  }
}
..

推荐答案

bar: Int

这几乎不是构造函数参数.如果未在构造函数以外的任何地方使用此变量,则该变量将保留在该变量中.没有生成任何字段.否则,将创建private val bar字段,并为其分配bar参数的值.没有创建吸气剂.

This is barely a constructor parameter. If this variable is not used anywhere except the constructor, it remains there. No field is generated. Otherwise private val bar field is created and value of bar parameter is assigned to it. No getter is created.

private val bar: Int

此类参数声明将使用私有getter创建private val bar字段.无论参数是否在构造函数旁边使用(例如,是否在toString()中使用),此行为都与上述行为相同.

Such declaration of parameter will create private val bar field with private getter. This behavior is the same as above no matter if the parameter was used beside the constructor (e.g. in toString() or not).

val bar: Int

与上面相同,但是类似Scala的getter是公开的

Same as above but Scala-like getter is public

bar: Int在案例分类中

涉及案例类时,默认情况下,每个参数都具有val修饰符.

When case classes are involved, by default each parameter has val modifier.

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

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