Scala高级02
一、重温
1、算子/函数/API
2、读取文件
(1)FileFrom
3、模式匹配
(1)teacher
(2)异常捕获
(3)偏函数
(4)其他函数:颗粒化currying、字符串插值 $
二、隐式转换(能不用就不用,可能你能cover住,但是你的小伙伴不一定能接住)
1、类,添加一个方法
可以用继承、装饰
代理:静态代理:继承
动态代理:JDK、CGLIB
隐式转换:偷偷的、不知不觉的给你实现了
2、定义隐式转换函数
implicit def dog2JoeyDog(dog: Dog):JoeyDog = new JoeyDog(dog.name)
总结:
1)关键字:implicit
2)返回的类型要在最后new出来
3、源码
object ImpliciApp { def main(args: Array[String]): Unit = { //定义隐式转换函数,普通狗2牛逼狗 implicit def dog2JoeyDog(dog: Dog):JoeyDog = new JoeyDog(dog.name) val dog = new Dog("若泽数据巨人的狗") dog.speak() } } class Dog(val name:String) class JoeyDog(val name: String){ def speak()={} println(s"$name 说:巨人是傻逼..") }
3、例子2
(1)添加一个RichFile的类,实现read的方法
(2)直接按alt+enter将java.io导进来
(3)注意返回值的类型
//File 添加一个read方法可以直接读取内容 class RichFile(val file:File){ def read() = { Source.fromFile(file.getPath).mkString }
(4)源码
package Day05 import java.io.File import scala.io.Source object FileImplicitApp { def main(args: Array[String]): Unit = { implicit def file2RichFile(file: File):RichFile = new RichFile(file) val file = new File("C:\\Users\\dell\\Desktop\\file.txt") val content = file.read() println(content) } } //File 添加一个read方法可以直接读取内容 class RichFile(val file:File){ def read() = { Source.fromFile(file.getPath).mkString//集合转字符串 } }
4、建议创建一个类专门存放隐式转换
import一下就可以了
5、占个坑:import ImpliticAspect._ spark SQL再讲
6、打开RDD源码