![](/img/trans.png)
[英]Does it make sense to have a `private` constructor field in a `case class`?
[英]Does it make sense to use “private[this] lazy val”?
我了解為什么這樣做有用
private[this] val xx = 3
如https://github.com/databricks/scala-style-guide#privatethis所述 。
lazy val
一樣嗎?
Q1。 是private[this] lazy val xx = 3
比private val xx = 3
快?
Q2。 def f(i: Int) = i
是private[this] lazy val xx = f(3)
比private val xx = f(3)
快?
否。對於private lazy val x= 3
和private[this] lazy val =3
的類,生成的類是相同的,說明如下。
private lazy val
public class LazyValTest
{
private int bar;
private volatile boolean bitmap$0;
private int bar$lzycompute()
{
synchronized (this) { if (!this.bitmap$0) { this.bar = 3; this.bitmap$0 = true; } return this.bar; } }
private int bar() { return this.bitmap$0 ? this.bar : bar$lzycompute();
}
}
使用private和private [this] val生成的類略有不同。
private val
public class PrivateValTest
{
private final int bar = 3;
private int bar() { return this.bar; }
}
private[this] val
public class PrivateThisValTest
{
private final int bar = 3;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.