gpt4 book ai didi

scala - val 和单例对象之间的细微差别是什么?

转载 作者:行者123 更新时间:2023-12-01 02:24:57 24 4
gpt4 key购买 nike

一个本质上类似于subtle differences between val and def的问题.我想知道拥有成员单例对象之间的语义区别是什么:

class Text {
...
object Whitespace { def unapply(s :String) =
if (s.forall(_.isWhitespace)) Some(s) else None
}
}


class Text {
...
val Whitespace = new { def unapply(s :String) =
if (s.forall(_.isWhitespace)) Some(s) else None
}
}

我知道两者如何转换为字节码,但是我可以用代码中的一个做什么而另一个不能?

最佳答案

您需要更加努力地覆盖成员对象。

apm@mara:~/tmp$ skala
Welcome to Scala version 2.11.0-20130622-103744-990c2b024a (OpenJDK 64-Bit Server VM, Java 1.7.0_21).
Type in expressions to have them evaluated.
Type :help for more information.

scala> class Foo1 { val foo = () => 1 }
defined class Foo1

scala> class Bar1 extends Foo1 { override val foo = () => 2 }
defined class Bar1

scala> class Foo2 { object foo { def apply() = 3 } }
defined class Foo2

scala> class Bar2 extends Foo2 { override object foo { def apply() = 4 }}
<console>:8: error: overriding object foo in class Foo2;
object foo cannot override final member
class Bar2 extends Foo2 { override object foo { def apply() = 4 }}
^

scala> :q
apm@mara:~/tmp$ skala -Yoverride-objects
Welcome to Scala version 2.11.0-20130622-103744-990c2b024a (OpenJDK 64-Bit Server VM, Java 1.7.0_21).
Type in expressions to have them evaluated.
Type :help for more information.

scala> class Foo2 { object foo { def apply() = 3 } }
defined class Foo2

scala> class Bar2 extends Foo2 { override object foo { def apply() = 4 }}
defined class Bar2

scala> new Bar2
res0: Bar2 = Bar2@508c825

scala> .foo()
res1: Int = 4

scala> :q

关于scala - val 和单例对象之间的细微差别是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17308141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com