首页 > 应用开发 > > scala隐式转换优先级问题
隐式转换编译器会优先选择方法的参数作为转换对象,验证如下:
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来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69927053/viewspace-3133348/ ,如需转载,请注明出处,否则将追究法律责任。