[英]Why can Scala and sbt compile this code?
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
則會導致相同的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.