隐式转换编译器会优先选择方法的参数作为转换对象,验证如下:
-
object rct {
-
-
-
implicit def intToBook(num:Int) = new Book(num)
-
implicit def bookToInt(book:Book) = book.number
-
-
class Book(val number:Int){
-
-
def + ( that : Book ) = new Book( this.number + that.number )
-
-
}
-
-
-
def main(args: Array[String]): Unit = {
-
-
-
val book1 = new Book(100)
-
val book2 = new Book(200)
-
-
val book3 = book1 + book2
-
println(book3.isInstanceOf[Book])
-
-
val book4 = book1 + 200
-
println(book4.isInstanceOf[Book])
-
-
val book5 = 200 + book1
- println(book5.isInstanceOf[Int])
-
print:
true
true
true
true
true
true
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29754888/viewspace-2137052/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29754888/viewspace-2137052/