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

nio*_*cer 2 scala compilation implicit sbt

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)
Run Code Online (Sandbox Code Playgroud)

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

但是,如果删除toTestMapped方法的"隐式",或者通过其他名称更改"otherProperty",则此代码不会编译.

我正在使用Scala 2.12.4.

小智 5

首先,通过定义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出现的问题,最终会遇到同样的问题