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

scala – 关于implicits的奇怪错误消息

发布时间:2020-12-16 18:47:31 所属栏目:安全 来源:网络整理
导读:scala implicit def transitive[A,B,C](implicit f: A = B,g: B = C): A = C = f andThen gtransitive: [A,implicit g: B = C)A = Cscala class Foo; class Bar; class Baz { def lol = println("lol") }defined class Foodefined class Bardefined class Ba
scala> implicit def transitive[A,B,C](implicit f: A => B,g: B => C): A => C = f andThen g
transitive: [A,implicit g: B => C)A => C

scala> class Foo; class Bar; class Baz { def lol = println("lol") }
defined class Foo
defined class Bar
defined class Baz

scala> implicit def foo2Bar(f: Foo) = new Bar
foo2Bar: (f: Foo)Bar

scala> implicit def bar2Baz(f: Bar) = new Baz
bar2Baz: (f: Bar)Baz

scala> implicitly[Foo => Baz]
<console>:14: error: diverging implicit expansion for type Foo => Baz
starting with method transitive in object $iw
              implicitly[Foo => Baz]

从上面的代码中可以明显看出,我正在尝试编写一个方法,该方法在范围内导入时会使隐式转换具有传递性.我期待这段代码可以工作,但令人惊讶的是它没有.上述错误消息的含义是什么,以及如何使此代码生效?

解决方法

更新:正如评论中所指出的,这种方法不能在2.8上编译,而是隐含地[Foo => Baz]正常工作,(新Foo).lol没有.

如果您将传递重命名为符合Predef中的方法,则此方法可以正常工作:

implicit def conforms[A,g: B => C): A => C = f andThen g

有关详细信息,请参见this answer.

作为旁注:使用-Xlog-implicits启动REPL是在这种情况下获取更多信息性错误消息的便捷方法.在这种情况下,起初并没有太多帮助:

scala> implicitly[Foo => Baz]
scala.this.Predef.conforms is not a valid implicit value for Foo => Baz because:
type mismatch;
 found   : <:<[Foo,Foo]
 required: Foo => Baz
<console>:14: error: diverging implicit expansion for type Foo => Baz
starting with method transitive in object $iw
              implicitly[Foo => Baz]
                        ^
scala.this.Predef.conforms is not a valid implicit value for Foo => Baz because:
type mismatch;
 found   : <:<[Foo,Foo]
 required: Foo => Baz
transitive is not a valid implicit value for Unit => Foo => Baz because:
not enough arguments for method transitive: (implicit f: A => B,implicit g: B => C)A => C.
Unspecified value parameter g.
transitive is not a valid implicit value for => Unit => Foo => Baz because:
not enough arguments for method transitive: (implicit f: A => B,implicit g: B => C)A => C.
Unspecified value parameter g.

但是如果我们暂时将foo2Bar和bar2Baz重写为函数,我们会收到一条错误消息,突出显示模糊性:

implicit val foo2Bar = (_: Foo) => new Bar
implicit val bar2Baz = (_: Bar) => new Baz

scala> implicitly[Foo => Baz]
transitive is not a valid implicit value for Foo => Baz because:
ambiguous implicit values:
 both method conforms in object Predef of type [A]=> <:<[A,A]
 and value foo2Bar in object $iw of type => Foo => Bar
 match expected type Foo => B

现在很明显我们只需要阴影一致.

(编辑:李大同)

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

    推荐文章
      热点阅读