设为首页 加入收藏

TOP

Scala隐式转换类遇到的问题
2015-02-03 22:27:31 来源: 作者: 【 】 浏览:26
Tags: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)如果不在同一个文件中,只需要在应用点之前进行导入即可;


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Linux程序存储结构 下一篇shell遍历一个日期范围

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: