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 现在很明显我们只需要阴影一致. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- bash – 使用set -o vi作为第一个交互式命令的ss
- Angular-Cli v1.6.6 Microsoft Edge浏览器的源映
- 【Angular 2+】使用<ng-content>实现嵌入包含(t
- angularjs – 如何在MEAN STACK Web应用程序中启
- 自动编译调试运行ASP.NET 4.0网站及用7zip按日期
- bash – 每个循环中shell脚本中的增量编号
- angular – 如何在量角器中禁用动画?
- Atlas学习手记(4):使用AutoComplete Extender
- 如何在vim中缩进特定的代码块?
- 权限管理系统--Bootstrap框架/JasigCAS单点登录/
热点阅读