2016-03-09 112 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