今天練習Scala的隱式轉換類遇到的一個問題,測試代碼如下:
object ImplcitTest {
def main(args: Array[String]) {
import Context._
val person1 = User("zhangsan")
println(person1.getStr())
val filePath = Thread.currentThread.getContextClassLoader.getResource("test.txt").getPath
println(filePath)
val readStr = new File(filePath).read()
println(readStr)
}
}
class RichFile(val file: File) {
def read(): String = Source.fromFile(file).mkString
}
object Context {
implicit def file2String(f: File) = new RichFile(f)
implicit def user2Person(str: User) = new Person(str.name, 21)
}
case class User(val name:String)
class Person(val name: String, val age: Int) {
def getStr(): String = this.toString
}
拋出了下面的異常:
Error:(13, 34) value getStr is not a member of com.test.scala.User
Note: implicit method user2Person is not applicable here because it comes after the application point and it lacks an explicit result type
val person1 = User("zhangsan").getStr()
^
它的意思是:隱式轉換方法user2Person方法應該在隱式轉換應用之前定義。
所以將代碼進行了如下修改,異常解決:
class RichFile(val file: File) {
def read(): String = Source.fromFile(file).mkString
}
object Context {
implicit def file2String(f: File) = new RichFile(f)
implicit def user2Person(str: User) = new Person(str.name, 21)
}
case class User(val name:String)
class Person(val name: String, val age: Int) {
def getStr(): String = this.toString
}
object ImplcitTest {
def main(args: Array[String]) {
import Context._
val person1 = User("zhangsan")
println(person1.getStr())
val filePath = Thread.currentThread.getContextClassLoader.getResource("test.txt").getPath
println(filePath)
val readStr = new File(filePath).read()
println(readStr)
}
}
由此得出的結論是:
1)如果隱式轉換的定義和應用在同一個文件中,則隱式轉換必須定義在應用點之前,並且在應用點之前需要進行導入;
2)如果不在同一個文件中,只需要在應用點之前進行導入即可;