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
,您创建了从Test
到TestMapped
的隐式转换。
其次,在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/