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

在Scala中隐含对象

发布时间:2020-12-16 18:59:47 所属栏目:安全 来源:网络整理
导读:我对Joshua Suareth的书 Scala中的“5.1.3隐式解决方案”中的描述感到困惑,第100页: Scala objects can’t have companion objects for implicits. Because of this,implicits associated with the object’s type,that are desired on the implicit scope
我对Joshua Suareth的书 Scala中的“5.1.3隐式解决方案”中的描述感到困惑,第100页:

Scala objects can’t have companion objects for implicits. Because of
this,implicits associated with the object’s type,that are desired on
the implicit scope of that object’s type,must be provided from an
outer scope. Here’s an example:

scala> object Foo {
     |   object Bar { override def toString = "Bar" }
     |   implicit def b : Bar.type = Bar 
     |}
defined module Foo
scala> implicitly[Foo.Bar.type]
res1: Foo.Bar.type = Bar

但是我在REPL中隐藏了对象Bar:

scala> object Foo {
     |   implicit object Bar {
     |     override def toString = "isBar" }
     | }
defined module Foo
scala> implicitly[Foo.Bar.type]
res0: Foo.Bar.type = isBar

似乎它不需要在外部范围中定义隐式.或者我认为约书亚的意思完全错了?

解决方法

在这种情况下,对象就好像它们是自己的伙伴一样,所以你只需要在对象本身的体内嵌套对象类型提示的含义,

scala> object Bar {
     |   override def toString = "Bar"
     |   implicit def b : Bar.type = Bar
     | }
defined module Bar

scala> implicitly[Bar.type]
res0: Bar.type = Bar

请注意,此处Bar的主体已被视为解析Bar.type的隐式范围的一部分.

这可能看起来是Scala类型系统的一个不起眼的角落,但我能够在shapeless的polymorphic (function) values编码中充分利用它.

(编辑:李大同)

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

    推荐文章
      热点阅读