参考资料:B站林子雨教学视频
var
可变val
不可变;字面量(literal)用val
val valDouble: Double = 10.6
var varStr: String = "Hello Scala!"
varStr = "Hello World!"
// valDouble = 10.8 不可更改
Byte Short Int Long
Char String
Float Double
Boolean
这些类型都是类
注意:操作符是方法
(5).+(3.5) == 5.5 + 3 // true
1 to 5
6.to(10)
1 until 5
1 to 10 by 2
0.5f to 6.0f by 0.5f
readByte, readShort, readInt, readLong, readFloat, readchar, readBoolean
等等print, println, prinf
var age = readInt()
var heavy = readFloat()
var str = readLine("Please input your name: ")
printf("My name is %s. I am %d years old and %.1f Kg.\n", str, age, heavy)
import java.io.PrintWriter
val out = new PrintWriter("output/output.txt")
for (i <- 1 to 5) out.println(1)
out.close()
import scala.io.Source
val inputFile = Source.fromFile("input/words.txt")
val lines = inputFile.getLines() // 返回的是一个迭代器
for (line <- lines) println(line)
Scala只有不受检查异常
var f: FileReader = null
try {
f = new FileReader("input.txt")
} catch {
case ex: FileNotFoundException =>
println("Exception: File Not Found!")
case ex: IOException =>
println("IO Exception!")
} finally {
try {
f.close()
} catch {
case ex: NullPointerException =>
println("Null Pointer Exception!")
}
}
语法同Java一样,但和Python一样可以赋值
val a = if (true) 1 else 0
var i = 3
while (i > 0) {
println(i)
i -= 1
}
do {
i -= 1
println(i)
} while (i > -3)
for (变量 <- 表达式) 语句块
for (i <- 1 to 5 by 2) println(i)
for (i <- 6 to 10 if i%2 == 0) println(i)
for (i <- 1 to 5 if i%2 == 0; j <- 6 to 10 if j%2 == 1)
println(i + "*" + j + "=" + i*j)
val r = for (i <- 1 to 10 if i%2 == 0) yield {println(i); i}
println(r) // Vector(2, 4, 6, 8, 10)
scala.collection.mutable
scala.collection.immutable
scala.collection.immutable.List
var strList = List("BigData", "Hadoop", "Spark")
for (item <- strList) println(item)
// tail输出除head之外的全部
strList.head, strList.tail
// (BigData,List(Hadoop, Spark))
// 把Apache插入到strList头部
var otherList = "Apache"::strList
for (item <- otherList) println(item)
val intList = 1::2::3::Nil
// 等效于 val intList = List(1, 2, 3)
scala.collection.immutable.Set
scala.collection.mutable.Set
var strSet = Set("Hadoop", "Spark")
var copySet = strSet
strSet += "Scala" // strSet指向变了, 即不再指向原先那个Set了
for (item <- strSet) println("new: " + item)
for (item <- copySet) println("copy: " + item)
// 声明可变集合 可 import; 也可 声明变量时写全名
// import scala.collection.mutable.Set
val mutableSet = scala.collection.mutable.Set("DataBase", "BigData")
val copyMutableSet = mutableSet
mutableSet += "Cloud Computing" // 指针指向没变,与它是val并不矛盾
for (item <- mutableSet) println("new: " + item)
for (item <- copyMutableSet) println("copy: " + item)
scala.collection.immutable.Map
scala.collection.mutable.Map
val university = Map("XMU" -> "Xiamen University",
"THU" -> "Tsinghua University",
"PKU" -> "Peking University")
val xmu = if (university.contains("XMU")) university("XMU") else 0
val university2 = scala.collection.mutable.Map("XMU" -> "XMU")
// 修改value
university2("XMU") = "Xiamen University"
// 新增键值对
university2("PKU") = "Peking University"
university2 += ("THU" -> "Tsinghua University")
university2 += ("SDU" -> "ShanDong University", "SJU" -> "Jiaotong University")
// Map的几种遍历方式
for ((k, v) <- university2) printf("Code is %s, Name is %s.\n", k, v)
for (kv <- university2) println(kv._1 + ": " + kv._2)
for (k <- university2.keys) println(k)
for (v <- university2.values) println(v)
var iter = Iterator("Hadoop", "Spark", "Scala")
while (iter.hasNext) {
println(iter.next())
}
// 迭代器已经到末尾了 必须重新赋值
iter = Iterator("Hadoop", "Spark", "BigData")
for (elem <- iter) println(elem)
grouped
val xs = List(1, 2, 3, 4, 5)
// 每两个一组
// 也可以写成 xs grouped 2
val git = xs grouped(2)
while (git.hasNext) {
println(git.next())
}
// List(1, 2)
// List(3, 4)
// List(5)
sliding
// 以3为滑动窗口size, 一直滑到end
val sit = xs sliding 3
while (sit.hasNext) {
println(sit.next())
}
// List(1, 2, 3)
// List(2, 3, 4)
// List(3, 4, 5)
new Array[type](length)
Array.ofDim[type](dim0, dim1, ...)
val intValueArr = Array(-12, 45, 33)
intValueArr(0) = 12
val strArr = new Array[String](3)
strArr(0) = "BigData"
strArr(1) = "Hadoop"
strArr(2) = "Spark"
// 数组遍历
for (i <- 0 to 2) println(intValueArr(i) + " " + strArr(i))
// 多维数组
val matrix = Array.ofDim[Int](3, 4)
val cube = Array.ofDim[Int](3, 4, 5)
不定长数组
val aMutableArr = ArrayBuffer(10, 20)
// 末尾追加50
aMutableArr += 50
for (num <- aMutableArr) println(num)
// 在第3个位置插入两个数
aMutableArr.insert(2, 30, 40)
for (num <- aMutableArr) println(num)
// 删去40这个数
aMutableArr -= 40
for (num <- aMutableArr) println(num)
// 移除第3个数
aMutableArr.remove(2)
for (num <- aMutableArr) println(num)
不同类型的值的聚集
val tuple = ("BigData", 2015, 45.0, true)
println(tuple._1 + " " + tuple._2 + " " + tuple._3 + " " + tuple._4)
在异常处理部分有简单涉及
// 有匹配值 输出red
val colorNum = 1
var colorStr = colorNum match {
case 1 => "red"
case 2 => "green"
case 3 => "yellow"
case _ => "Not Allowed"
}
println(colorStr)
// 可捕获值并利用该值
colorStr = 4 match {
case 1 => "red"
case 2 => "green"
case 3 => "yellow"
case unexpected => unexpected + " is Not Allowed"
}
println(colorStr)
// 也可以match类型
for (elem <- List(3, 9.3, "Spark", "Hadoop", true)) {
val str = elem match {
case i: Int => i + " is an int value."
case d: Double => d + " is a double value."
case "Spark" => "Spark is found."
case s: String => s + " is a string value."
case _ => "This is an unexpected value."
}
println(str)
}
// 支持条件过滤
for (elem <- List(1, 2, 3, 4)) {
elem match {
case _ if (elem%2 == 0) => println(elem + " is even.")
case _ => println(elem + " is odd.")
}
}
// case类的匹配
case class Car(brand: String, price: Int)
val myBYDCar = new Car("BYD", 89)
val myBMWCar = new Car("BMW", 120)
val myBenzCar = new Car("Benz", 150)
case class Car(brand: String, price: Int)
val myBYDCar = new Car("BYD", 89)
val myBMWCar = new Car("BMW", 120)
val myBenzCar = new Car("Benz", 150)
for (car <- List(myBYDCar, myBMWCar, myBenzCar)) {
car match {
case Car("BYD", 89) => println("Hello, BYD")
case Car("BMW", 120) => println("Hello, BMW")
case Car(brand, price) => println("Brand: " + brand + ", Price: " + price + ", do you want it?")
}
}
val books = Map("Hadoop" -> 5, "Spark" -> 10, "HBase" -> 7)
println(books.get("Hadoop")) // Some(5)
val sales = books.get("Hive")
println(sales) // None
// 把None转化为No Such Book
println(sales.getOrElse("No Such Book"))
println(List(1, null).foreach(println))
// 1
// null
// () foreach遇到None的时候