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

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

问题描述

我一直在尝试:

class Foo(bar: Int)

对比:

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 参数的值分配给它.没有创建 getter.

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 in case classes

bar: Int in case classes

当涉及 case 类时,默认每个参数都有 val 修饰符.

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

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

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