scala学习记录二

模式匹配

  • Java:对一个值对象条件判断,返回针对不同的条件进行不同的处理
  • scala:
    变量 match{ case value1 => 代码1 case value2 => 代码2 case _ => 代码N

简单的switch case
object MatchAppextendsApp{ val names = Array("Akiho Yoshizawa","YuiHatang","Aoi Sola"); val name = names(Random.nextInt(names.length)); // 随机选name match { case "Akiho Yoshizawa" => println("吉老师。。。。") case "YuiHatang" => println("波老师。。。") case _ => println("不知道你们在说什么") }def judgeGrade(grade:String):Unit={ grade match { case "A" => println("很好...") case "B" => println("还可以。。。") case "C" => println("一般。。。") case _ => println("需要努力。。。") } }judgeGrade("A") judgeGrade("B") judgeGrade("D") }

双重过滤
def judgeGrade(grade:String,name:String):Unit={ grade match { case "A" => println("很好...") case "B" => println("还可以。。。") case "C" => println("一般。。。") case _if(name == "lisi") => println(name + "你是一个good boy 不过 需要努力。。。") case _=> println("需要努力。。。") } } judgeGrade("D","zhangsan") judgeGrade("A","lisi") judgeGrade("D","lisi")

数组过滤
def greeting(array:Array[String])={ array match { case Array("zhangsan") => println("Hi: zhangsan"); // 如果数组中有张三 case Array(x,y) => println("Hi: "+ x + " , "+y); // 打印含有两个元素的数组 case Array("zhangsan",_*) => println("Hi: zhangsan and other friend" ) // zhangsan开头的数组元素 case _ => println("Hi: everybody...") } } greeting(Array("zhangsan")) //Hi: zhangsan greeting(Array("lisi","wangwu","zhaoyun")) //Hi: everybody... greeting(Array("zhangsan","lisi","wangwu")) // Hi: zhangsan and other friend

List过滤
def greeting(list:List[String])={ list match { case "zhangsan" ::Nil => println("Hi:zhangsan"); case x::y::Nil => println("Hi: "+ x + ", "+y); //只有两个元素 case "zhangsan"::tail => println("Hi zhangsan and other firends..") // 头加尾 case _ => println("HI: everybody...") } } greeting(List("zhangsan")); //Hi:zhangsan greeting(List("lisi","zhangsan")); // Hi: lisi, zhangsan greeting(List("zhangsan","lisi")) // Hi: zhangsan, lisi greeting(List("zhangsan","lisi","aa")) // Hi zhangsan and other firends..

类型匹配
def matchType(obj:Any)={ obj match { case x:Int => println("Int"); case x:String => println("String"); case x:Map[_,_] => x.foreach(println); case _ => println("other type") } } matchType(1); //Int matchType("1") // String matchType(1f) // other type matchType(Map("name"->"PK")) //(name,PK)

异常处理
object ExceptionApp extendsApp { try { val i = 10/0; }catch { case e:ArithmeticException => println("除数不能为0。。。") case e: Exception => println(e.getMessage) } finally { //释放资源 }

case class模式匹配
def caseclassMatch(person: Person)={ person match { case CTO(name,floor)=>println("Cto name is: "+name+" , floor is "+floor) case Employee(name,floor)=>println("Employee name is: "+name+" , floor is "+floor) case _ => println("other") } } class Person; case classCTO(name:String,floor:String) extends Person; case classEmployee(name:String,floor:String) extends Person; case classOther(name:String) extends Person; caseclassMatch(CTO("PK","12 ")) caseclassMatch(Employee("zhangsan","2 ")) caseclassMatch(Other("other"))

scala函数高级
字符串高级操作
val s = "Hello:PK" val name = "PK" println(s+name) println(s"Hello:$name")var team = "AC Milan" // 插值 println(s"Hello:$name,Welcome to $team") //多行字符串 val b = """ |这是一个多行字符串 |hello |world |PK |""".stripMargin println(b)

匿名函数
def sayHello(name:String)={ println(s"hi: $name") } sayHello("PK") //hi: PK val sayHello2 = (name:String)=>println(s"Hi: $name") sayHello2("zhangsan") //Hi: zhangsan

函数柯里化(curring)
def sum(a:Int,b:Int) = a+b println(sum(2,3 ))def sum2(a:Int)(b:Int)=a+b println(sum2(2)(3))

高阶函数
val l= List(1,2,3,4,5) //map:逐个去操作集合中的每个元素 //val l2 = l.map((x:Int)=>x+1) // 每个元素加一 val l2 = l.map(x=>x+1) // 参数为一个元素,括号可省略 val l3 = l.map(_ + 1) // 占位符表示任意一个元素,既每个元素加一 println(l2) //List(2, 3, 4, 5, 6) println(l3) //List(2, 3, 4, 5, 6)val l4 = l.map(_ + 1).filter(_ > 5) // 加一后,取出大于5的元素 println(l4) //List(6)val l5 = l.take(2) // 取前两个元素 println(l5) //List(1, 2) // 1+2 3+3 6 + 4 val l6 = l.reduce(_+_) // 相邻求和 println(s"reduce $l6") //reduce 15//reduceLeft = ((((1-2)-3)-4)-5) 其实调用的flodLeft val l7 = l.reduceLeft(_-_) println(s"reduceLeft $l7") // reduceLeft -13 //reduceRight = (1-(2-(3-(4-5)))) 其实调用的flodRight val l8 = l.reduceRight(_-_) println(s"reduceRight $l8") // reduceRight 3// fold 计算公式为 0 - 1 -2 -3 - 4 - 5 val l9 = l.fold(0)(_-_) println(s"fold $l9") // fold -15val l10 = l.foldLeft(0)(_-_) println(s"foldLeft $l10") //foldLeft -15val f = List(List(1,2),List(3,4),List(5,6)) println(f.flatten)// 展平 List(1, 2, 3, 4, 5, 6)// flatMap println(f.map(_.map(_*2)))// List(List(2, 4), List(6, 8), List(10, 12)) println(f.flatMap(_.map(_*2))) // List(2, 4, 6, 8, 10, 12)val text = scala.io.Source.fromFile(path+"\\hello.txt").mkString println(text) //hello,world,hello,helloval texts = List(text) var texts1 = texts.flatMap(_.split(",")).map(x=>(x,1)) println("groupBy: "+texts1.groupBy((_._1))) //groupBy: Map(world -> List((world,1)), hello -> List((hello,1), (hello,1), (hello,1)))println("Key: "+ texts1.map(_._1)) //_1 相当于key // Key: List(hello, world, hello, hello)println("Value: "+ texts1.map(_._2)) //_2 相当于value Value: List(1, 1, 1, 1)// groupBy 按key分组 //第一个占位符表示含有(key,1)的list,经过groupBy后分为不同的(key1,value),(key2,value)println(texts1.groupBy(_._1).mapValues(_.foldLeft(0)(_+_._2))) // 统计词频 //Map(world -> 1, hello -> 3)

偏函数
/* 偏函数:被包在花括号内没有 match的一组Case语句 */object PartitalFunctionApp extendsApp{// 第一个输入参数类型,第二个是返回类型 def sayChinese:PartialFunction[String,String] ={ case "Akiho Yoshizawa" => ("吉老师。。。。") case "YuiHatang" => ("波老师。。。") case _ => ("不知道你们在说什么") } println(sayChinese("Akiho Yoshizawa")) }

隐式转换
【scala学习记录二】需求:为一个已存在的类添加一个新的方法(第三方的类)
  • java: 动态代理
  • Scala: 隐式转换
隐式转换测试
object ImplicitAppextendsApp {// 定义隐式转换函数 implicit def man2superman(man:Man): Superman = new Superman(man.name)val man = new Man("PK") man.fly()implicit def file2richFile(file:File): RichFile = new RichFile(file) val file = new File(path+"\\hello.txt") println(file.read()) }class Man(val name:String){ def eat()={ println(s"man [ $name ] eat....") } }class Superman(val name:String){ def fly()={ println(s"superman [ $name ] fly....") } }class RichFile(val file:File){ def read()={ scala.io.Source.fromFile(file.getPath).mkString } }

隐式参数 指的是在函数或者方法中,定义一个用 implicit修饰的参数,此时Scala会尝试找到一个指定类型的,用 implicit修饰的对象,即隐式值,并注入参数
def testParam(implicitname:String)={ println(name + "~~~~~~~~~") } //testParam("张三") implicitval name1 = "implicit_name" // 这里需要注意,不可以定义多个隐式参数 testParam

隐式类
object ImplicitClassApp extends App { implicit class Calculator(x:Int){ def add(a:Int) = a+x } println(12.add(3)) // 可以不创建对象,直接调用类中的方法 }

操作外部数据
读取文件
def main(args: Array[String]): Unit = {val file = Source.fromFile(path+"\\hello.txt")(scala.io.Codec.UTF8)// 按行读取 def readLine(): Unit ={ for(line <- file.getLines()) println(line) } // 按字符读 def readChar(): Unit ={ for(ele <- file){ println(ele) } }// 读取网络 def readNet(): Unit ={ val file = Source.fromURL("http://www.baidu.com") for(line <- file.getLines()) println(line) } readNet() }

    推荐阅读