加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – val和singleton对象之间的细微差别是什么?

发布时间:2020-12-16 08:48:37 所属栏目:安全 来源:网络整理
导读:一个问题本质上类似于 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
一个问题本质上类似于 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读