/** * 测试 for 循环 */ def testFor(){ for(i <- 1 to 10){ println("number is :"+i) }
for(i <- 1 to 2; j <- 1 to 2) print(i*100 + j+" ")
for(i <- 1 to 2; j <- 1 to 2 if i != j) print(i*100 + j+" ")
}
2.测试增强 for 循环
/** * 测试增强 for 循环 */ def testFor2(){ var files = new java.io.File("D:/").listFiles() for(file <- files){ // println(file) } }
3.测试 if
/** * 测试 if */ def testIf(){ def file = "" def str = if(file != "") file else "b.txt" print(str) }
4.
/** * 测试 Tuple (元组) */ def tuple(){ val pair = (100, "scala", "spark") println(pair._1+" "+pair._2+" "+pair._3) }
5. 测试 map
/** * 测试 map */ def testMap(){ val tMap = Map("scala" -> 20, "spark" -> 30) for((k, v) <- tMap){ println("key is:" +k +" value is:"+v) } //循环 key for((k,_) <- tMap){ println("key is:"+k) } //循环 value for((_,v) <- tMap){ println("value is:"+v) } }
6. 测试 数组
/** * 测试 数组 */ def testArray(){ val array = Array(1,2,3,4,5) for(i <- 0 until array.length){ print(array(i)) } println() for(tem <- array){ print(tem) } println() }
7. scala 读取文件
/** * scala 读取文件 */ def testFile(){ val file = Source.fromFile("D:/a.txt")
// val file = Source.fromURL("http://www.youku.com") for(line <- file.getLines()){ println(line) } }
8. 函数
def addA(x: Int) = x + 100 //匿名函数 var add = (x:Int) => x+200 print(add(2))
9. 递归函数
def fac(n:Int):Int = if(n <= 0) 1 else n*fac(n-1) println(fac(10))
10. 有参函数
def combine(content:String, left:String, right:String) = left+content+right println(combine("test", "[","]"))
def combine(content:String, left:String="[", right:String="]") = left+content+right
println(combine("test"))