目录
4.案例:File中没有read方法,通过隐式转换使用read方法
1.偏函数 PartialFunction
- 用法
定一个方法,返回值是偏函数{
方法体:一对case语句
}
A:表示输入参数类型
B:表示输出参数类型 - 命令
object T1 { def main(args: Array[String]): Unit = { val course = Array("spark","fink","hive") val item: String = course(Random.nextInt(course.length)) println(teacher(item)) } def teacher:PartialFunction[String,String]={ case "spark" => "批流一体框架" case "hive" => "离线计算框架" case _ => "其他计算框架" } }
2.柯力化 currying
- 意义:是必然发生的结果
- 命令
- def sum(x:Int,y:Int)
- def sum(x:Int)(y:Int)
object T2 { def main(args: Array[String]): Unit = { println(sum1(1,3)) //4 println(sum2(1)(2)) //3 } def sum1(x:Int,y:Int)={ x+y } def sum2(x:Int)(y:Int)={ x+y } }
3.读取文件内容:io
object T3 {
def main(args: Array[String]): Unit = {
val content: BufferedSource = Source.fromFile("data/wc.data")
val lines = content.getLines()
for (elem <- lines) {
println(elem)
}
}
}
- 案例:读取文件内容,统计每个单词出现的次数 结果数据输出到控制台,安装单词次数降序排序
object T3_1 { def main(args: Array[String]): Unit = { val wordcount: BufferedSource = Source.fromFile("data/wc.data") val lines = wordcount.getLines() lines.toArray.flatMap(_.split(",")).map((_,1)).groupBy(_._1).map(x => (x._1 , x._2.length)).toArray.sortBy(s => -s._2).foreach(println(_)) } }
4.隐式转换
-
1.目的:增强
- A类 =》 B类
B对A已有的东西进行增强 【感知不到】
- A类 =》 B类
-
2.代码
object T4 { def main(args: Array[String]): Unit = { //隐式转换 implicit def man2superman(man:Man):SuperMan={ new SuperMan(man.name) } val lili = new SuperMan("lili") lili.fly() val lsz = new Man("lsz") lsz.fly() } class Man(val name:String) class SuperMan(name:String){ def fly()={ println(s"${name} can fly") } } }
-
3.隐式转换
- 1.隐式参数:作用到方法参数上
- 2.隐式类型转换:作用到def上(常用的)
- 3.隐式类:作用到class上 (是高危的)
-
4.案例:File中没有read方法,通过隐式转换使用read方法
object T4_1 { def main(args: Array[String]): Unit = { implicit def file2RichFile(file:File):RichFile={ new RichFile(file) } val file = new File("data/wc.data") println(file.read()) } class RichFile(file:File){ def read()={ Source.fromFile(file.getPath).mkString } } }
5.泛型
-
1.命令
object T5_1 { def main(args: Array[String]): Unit = { val tiantian = new GG[FaceValueEnum, Int, Double](FaceValueEnum.A, 181, 8) val yuwenxin = new GG[FaceValueEnum, Int, Double](FaceValueEnum.A, 160, 10) println( s""" |${tiantian} |${yuwenxin} |""".stripMargin) } class GG[A,B,C](val faceValue:A,val heigh:B,val chuan:C){ override def toString:String = faceValue+"\t" + heigh +"\t" + chuan } object FaceValueEnum extends Enumeration{ type FaceValueEnum = Value val A,B,C,D = Value } }
-
2.java和scala上下界
- 上界
<T extends Test>
T 是Test的子类
<? extends Test> - 下界
<T super Test>
T 是Test的子类
<? super Test>
- 上界
-
3.逆变 协变 【了解】
- - +
6.scala排序
- java
- Comparator
- Comparable
- scala
- Ordering => Comparator
- Ordered => Comparable