scala - 为什么Scala和sbt可以编译这段代码?

标签 scala compilation sbt implicit

Scala 工作表示例

case class Test(name: String)

case class TestMapped(name: String,
                      otherProperty: String)

protected implicit def toTestMapped(test: Test): TestMapped = {
  TestMapped(name = test.name,
             otherProperty = test.otherProperty)
}

val test = Test(name = "bug")
val testMapped = toTestMapped(test)

如果类 Test 中不存在“otherProperty”,为什么 Scala 和 sbt 可以编译此代码? 此代码以严重运行时错误结束:java.lang.StackOverflowError

但是,如果您删除 toTestMapped 方法的“隐式”,或将“otherProperty”更改为其他名称,则此代码将无法编译。

我使用的是 Scala 2.12.4。

最佳答案

首先,通过定义implicit def toTestMapped,您创建了从TestTestMapped的隐式转换。

其次,在test.otherProperty中。由于 test 是一个 Test 对象并且没有 otherProperty,scala 将查找作用域中的隐式转换并找到将进行类型检查的 toTestMapped。现在 test.otherProperty 可以被视为 toTestMapped(test).otherProperty,其中 toTestMapped(test) 将无限期地调用自身,最终会出现 stackoverflow 异常。

现在,如果您删除隐式,test.otherProperty 将无法编译,因为 Test 对象没有 val 或 def otherProperty 并且编译器找不到任何隐式转换。 同样,如果您在任一位置重命名 otherProperty,编译器将无法找到该名称。但是,如果您替换所有出现的 otherProperty,您最终会遇到相同的问题

关于scala - 为什么Scala和sbt可以编译这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48811205/

相关文章:

scala - Scala Lift 布线给我带来了什么?

scala - 更新不可变 AST 的最简单方法是什么?

java - 如何使用相同的库在 Eclipse 中编译和运行?

c++ - 使用 TCL/TK8.4 编译 c++ 应用程序以便它可以在 TCL/TK8.5 系统上运行的正确方法是什么?

c++ - 在 Linux 终端上使用 C++ 编译示例 opengl 应用程序

java - 有没有办法使用 playframework 接受路由中的自定义对象?

scala - 重置 SBT 中的列表设置

scala - 为什么在 Option[T] 的 HList 上映射不起作用?

scala - 如何在选项[String]中设置字符串?

scala - 如何让 sbt 停止尝试对每个构建拉取最新的传递范围依赖