package com.ws.spark.study.scala import java.io.File import org.scalatest.FlatSpec import scala.io.source class TestScala extends FlatSpec{ "for循环" should "成功" ignore { // 1. for中增加多个过滤 val files = new File(".").listFiles() for( file <- files if file.getName.endsWith(".xml"); if file.isFile){ println(file) } // 2. 多重for循环 def fileLines(file: File) = Source.fromFile(file).getLines().toList def grep(pattern: String) = for{ file <- files if file.getName.endsWith(".xml") line <- fileLines(file) if line.trim.matches(pattern)}{ println(s"$file:${line.trim}") } grep("xml") // 3. 生成返回结果(Array[File] => Array[Int]的转换) val forLineLengths = for { file <- files if file.getName.endsWith(".xml") line <- fileLines(file) trimmed = line.trim if trimmed.matches(".*for.*") } yield trimmed.length } "list列表" should "success" ignore { // 1. 与Array不同的是,List中的值不能改变 // 2. List具有协变性(Covariant),即类型S和T,如果S是T的子类,则List[S]也是List[T]的子类 val list1: List[Object] = List("hello", "world") // 空List的类型为nothing,nothing是Scala继承层次中的最底层 var list2: List[String] = List() } "函数参数" should "success" ignore { // 函数作为参数 def convertIntToString(f: Int => String) = f(4) // 函数f作为参数 val func = (x: Int) => s"$x s" println(convertIntToString(func)) // 4 s // 高阶函数可以产生新的函数 def multiplyBy(factor: Double) = (x: Double) => factor * x val func2 = multiplyBy(10) func2(50) } "函数闭包" should "success" ignore { // 在运行时确定more类型及值得函数称为闭包, more是个自由变量,在运行时其值和类型得以确定 // 这是一个由开放到封闭的过程,因此称为闭包 var more = 1 def func = (x: Int) => x + more println(func(10)) more = 20 println(func(10)) } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。