Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Scala隐式转换类遇到的问题

今天练习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)如果不在同一个文件中,只需要在应用点之前进行导入即可;本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-02/112787.htm