2016-03-09 110 views
-1

這裏是簡單的代碼和問題相關的位。斯卡拉類型轉換使用隱式 - >強制類型檢查

有沒有辦法告訴scala編譯器,如果這種轉換將被應用到的類型不存在,那麼編譯時會出錯!

我可以在sbt工具中看到警告,但看不到任何描述如此之戰。

class A(val n: Int) { 
    def +(other: A) = new A(n + other.n) 
} 

object A { 
    implicit def fromMyInt(n: Int) = new A(n) 
} 

val r = 1 + new A(1) 

println(r) 

回答

2

Scala編譯器已經這樣做了。

下面是一個示例文件,test.scala,試圖不可用的隱式轉換:

class A(val n: Int) { 
    def +(other: A) = new A(n + other.n) 
} 

object A { 
    implicit def fromMyInt(n: Int) = new A(n) 

    def main(args: Array[String]) = { 
    println(1 + new A(1)) 
    println(1.0 + new A(1)) 
    } 
} 

試圖編譯此給出了一個錯誤:

➤ scalac test.scala 
test.scala:10: error: overloaded method value + with alternatives: 
    (x: Double)Double <and> 
    (x: Float)Double <and> 
    (x: Long)Double <and> 
    (x: Int)Double <and> 
    (x: Char)Double <and> 
    (x: Short)Double <and> 
    (x: Byte)Double <and> 
    (x: String)String 
cannot be applied to (A) 
    println(1.0 + new A(1)) 
       ^
one error found 
+0

好了,不能看到SBT工具這個錯誤。但我知道你的意思:運行它像:scalac -feature main.scala ..然後我有一個錯誤。謝謝,這會做! – Pavel