第59讲:Scala中隐式转换初体验
2015-09-17 00:17
176 查看
今天学习了下隐式转换的内容。所谓隐式转换,就是说,一个实例拥用1 2 3方法,但是当它需要4方法的时候,它没有,但是却可以通过转换成另一种类型来调用4方法,而且这种转换是自动转换不需要人为干预的,这种形为就叫做隐式转换。让我们通过实例来分析一下:
import java.io.File
import scala.io.Source
class RichFile(val file:File){
def read = Source.fromFile(file.getPath).mkString
}
object Context{
implicit def file2RickFile(file:File) = new RichFile(file)//将File转换成RichFile
}
object test59 {
def main(args:Array[String]){
import Context.file2RickFile
println (new File("E:\\text.txt").read)
}
}
首先,我们定义一个class RichFile,当的参数类型是File,类拥有read方法。
然后定义一个单例对像Context,它拥有一个隐式方法,file2RichFile,此方法会将File类型的file传给类RichFile,实例化成RichFile的对像。
然后在main方法中,我们导入此方法。
接着,我们新建一个File类型的对像,让它去调用read方法。但是此file没有read方法,这时,编译器会在main方法体内寻找可以实现read方法的方法,也就是file2RichFile,通过此方法,将file实例化成RichFile的对像,这时,RichFile类型的file就拥有了read方法,可以正常调用了。
分享下更多的scala资源吧:
1,《Scala深入浅出实战经典》http://pan.baidu.com/s/1pJnAUr5
2,《Spark纯实战公益大讲坛》http://pan.baidu.com/s/1sLeVk
3,《Docker公益大讲坛》http://pan.baidu.com/s/1hq0GztU
4,《spark亚太研究院spark公益大讲堂》http://pan.baidu.com/s/1i30Ewsd
5, DT大数据梦工厂spark和scala的所有视频、PPT和代码在百度云盘的链接:http://pan.baidu.com/share/home?uk=4013289088#category/type=0&qq-pf-to=pcqq.group
import java.io.File
import scala.io.Source
class RichFile(val file:File){
def read = Source.fromFile(file.getPath).mkString
}
object Context{
implicit def file2RickFile(file:File) = new RichFile(file)//将File转换成RichFile
}
object test59 {
def main(args:Array[String]){
import Context.file2RickFile
println (new File("E:\\text.txt").read)
}
}
首先,我们定义一个class RichFile,当的参数类型是File,类拥有read方法。
然后定义一个单例对像Context,它拥有一个隐式方法,file2RichFile,此方法会将File类型的file传给类RichFile,实例化成RichFile的对像。
然后在main方法中,我们导入此方法。
接着,我们新建一个File类型的对像,让它去调用read方法。但是此file没有read方法,这时,编译器会在main方法体内寻找可以实现read方法的方法,也就是file2RichFile,通过此方法,将file实例化成RichFile的对像,这时,RichFile类型的file就拥有了read方法,可以正常调用了。
分享下更多的scala资源吧:
1,《Scala深入浅出实战经典》http://pan.baidu.com/s/1pJnAUr5
2,《Spark纯实战公益大讲坛》http://pan.baidu.com/s/1sLeVk
3,《Docker公益大讲坛》http://pan.baidu.com/s/1hq0GztU
4,《spark亚太研究院spark公益大讲堂》http://pan.baidu.com/s/1i30Ewsd
5, DT大数据梦工厂spark和scala的所有视频、PPT和代码在百度云盘的链接:http://pan.baidu.com/share/home?uk=4013289088#category/type=0&qq-pf-to=pcqq.group
相关文章推荐
- python相关——如何安装pip
- linux基础命令学习
- Windows下使用Dev-C++开发基于pthread.h的多线程程序
- sqoop出错,读不了mysql
- 【剑指Offer】斐波那契数列
- 71个单词搞定全部职位说法
- 工程架构方向需要关注的几个顶级会议
- UIImage+ImageEffects的category 模糊效果
- POJ1157LITTLE SHOP OF FLOWERS【dp】
- Laravel-5.1 ---- 将mews captcha整合到项目中!
- 设计模式之装饰模式(iOS开发,代码用Objective-C展示)
- A012-anim资源
- Leetcode Path Sum
- 使用AFNetworking进行序列化
- KMP算法详解
- Lucene索引创建过程2
- Tomcat 端口变更失效的问题的解决经历
- iOS Dev (27) 初步了解下UIView的最常用知识
- http协议
- Lucene索引创建过程