gpt4 book ai didi

scala 隐式完成自身?

转载 作者:行者123 更新时间:2023-12-04 20:35:18 26 4
gpt4 key购买 nike

我使用这种行来测试我的隐含内容,使其通过复制粘贴事故隐含。我花了很长时间才弄明白,尽管我不希望它编译,但为什么它会编译:

> console
[info] Starting scala interpreter...
[info]
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_66).
... skipped some comment lines ...

scala> case object Foo
defined object Foo

scala> object Bar { implicit val f: Foo.type = implicitly[Foo.type] }
defined object Bar

scala> val x = Bar.f
x: Foo.type = null

scala>

我希望 Bar 编译失败,因为没有类型 Foo.type 的隐式 val (case 对象未声明为隐式)。

对我来说,编译器似乎使用 f 自己的声明(左侧)来完成其实现(右侧)。

这真的是预期的行为吗?在运行时,这会导致 null 出现意外行为。值(对我来说主要是 NPE)。

最佳答案

这是因为 f声明为 implicit .所以在某种程度上是 implicit val f: Foo.type = implicitly[Foo.type] 的右手边解析为隐式 val f本身!

如果删除 implicit从那一行开始,编译将失败。
我想知道的是你为什么要使用这样一条线。

这对我来说绝对是个问题。不过,去年似乎有人已经记下了。

Enhancement Request

关于scala 隐式完成自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37022552/

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