Scala隐式转换类遇到的问题
2015-02-03 12:00
459 查看
今天练习Scala的隐式转换类遇到的一个问题,测试代码如下:
抛出了下面的异常:
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方法应该在隐式转换应用之前定义。
所以将代码进行了如下修改,异常解决:
由此得出的结论是:
1)如果隐式转换的定义和应用在同一个文件中,则隐式转换必须定义在应用点之前,并且在应用点之前需要进行导入;
2)如果不在同一个文件中,只需要在应用点之前进行导入即可;
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)如果不在同一个文件中,只需要在应用点之前进行导入即可;
相关文章推荐
- 在使用EF开发时候,遇到 using 语句中使用的类型必须可隐式转换为“System.IDisposable“ 这个问题。
- Related to Oracle SQL 关于遇到Number型与varchar2型比较时的隐式转换引起的生产问题
- Scala进阶之隐式转换作用域等问题
- 使用Mencoder进行视频转换遇到的问题和相关解决方案
- ajax打印对象时,转换由java对象转为Json格式的String时遇到的Hibernate问题
- 不要在一棵树上吊死——有感于视频转换遇到的一个问题
- 一个sql中常遇到的表结构转换问题
- 一个sql中常遇到的表结构转换问题
- Hyper-V P2V转换遇到的问题
- 字符串内码的转换,是开发中经常遇到的问题。
- .net类型自定义隐式(显式)转换操作的位置问题
- VC6和VS2003 转换到VS2005 时可能会遇到的问题以及解决方法
- 隐式类型转换的问题
- sizeof()使用请注意类型隐式转换问题
- 关于Use MFC in a Shared DLL和Use MFC in a Static Library 转换遇到的问题
- DB2中bigInteger的数据转换成char遇到的问题
- 显-隐式转换问题
- 隐式类型转换问题!
- 一个sql中常遇到的表结构转换问题
- 今天在csdn上遇到一个问题,是关于sql数据行列转换的,我的写法如下: