scala隱式轉換優先順序問題

破棉襖發表於2017-04-11

隱式轉換編譯器會優先選擇方法的引數作為轉換物件,驗證如下:

  1. object rct {


  2.   implicit def intToBook(num:Int) = new Book(num)
  3.   implicit def bookToInt(book:Book) = book.number

  4.   class Book(val number:Int){

  5.     def + ( that : Book ) = new Book( this.number + that.number )

  6.   }

  7.   
  8.   def main(args: Array[String]): Unit = {


  9.      val book1 = new Book(100)
  10.      val book2 = new Book(200)

  11.      val book3 = book1 + book2
  12.      println(book3.isInstanceOf[Book])

  13.      val book4 = book1 + 200
  14.      println(book4.isInstanceOf[Book])

  15.      val book5 = 200 + book1 
  16.      println(book5.isInstanceOf[Int])

print:

true
true
true



來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29754888/viewspace-2137052/,如需轉載,請註明出處,否則將追究法律責任。

相關文章