变量定义
Scala有两种变量,val和var。val类似于Java中的final变量,一旦初始化了,val就不能再被赋值。var可以多次赋值。但由于函数式编程特性,Scala更推崇val。
var的使用也有其局限性,Scala有类型推断的功能,当var被初始化后,其类型就已经被断定,比如
当m被赋值hello后,其被推断为String类型,此时再对m重新赋值,如果不是String类型则会报错:
函数定义
函数定义用def,如:
其中Unit类似于Java中的void。
以上是无参无返回值的最简单的函数,那么有参有返回值表达如下:
编写Scala脚本
编写hello.scala,内容如下:
println(args(0))
运行:
用while做循环,if做判断
在printargs.scala中输入:
var i = 0
while (i < args.length) {
println(args(i))
i += 1
}
执行结果:
用foreach和for做枚举
编写脚本echoargs.scala:
args.foreach(a => println(a))
for(i <- 0 to 3) {
println(i)
}
(0 to 3).foreach(i => println(i))
(4 until 6).foreach(println)
执行如下:
数组
编写arrays.scala:
val strArr = new Array[String](3)
strArr(0) = "Hello "
strArr(1) = "World"
strArr(2) = "~~~"
strArr.foreach(print)
println
strArr.update(2, "!")
strArr.foreach(print)
println
val apply = strArr.apply(1)
println("apply:" + apply)
val arr1 = Array(5, 2, 0)
arr1.foreach(print)
运行如下:
List
编写list.scala:
// 追加元素
val hello = List("World")
val strings = "Hello" :: hello
strings.foreach(println)
// 空列表Nil
val intList = 1 :: 2 :: Nil
// 追加List
val oneTwoThree = List(1, 2, 3)
val fourFiveSix = List(4, 5, 6)
val mix = oneTwoThree ::: fourFiveSix
mix.foreach(println)
运行如下:
Tuple(元组)
编写tuple.scala:
val tuple = (1, "a")
println(tuple._1)
println(tuple._2)
运行如下:
Set和Map
编写set_map.scala:
// 不可变Set
var jetSet = Set("Hi", "yan")
jetSet += "~~"
print(jetSet.contains("~~"))
println()
import scala.collection.mutable
// 可变Set
val mutableSet = mutable.Set("a", "b")
mutableSet += "c"
println(mutableSet)
val immutableMap = Map(1-> "a", 2-> "b", 3-> "c")
println(immutableMap(3))
val mutableMap = mutable.Map[Int, String]()
mutableMap += 1 -> "aa"
mutableMap += 2 -> "bb"
mutableMap += 3 -> "cc"
println(mutableMap(1))
运行:
文件读取
编写source.scala:
import scala.io.Source
def widthOfLength(s: String) = s.length.toString.length
if (args.length > 0) {
val lines = Source.fromFile(args(0)).getLines().toList
val longestLine = lines.reduceLeft(
(a, b) => if (a.length > b.length) a else b
)
val maxWidth = widthOfLength(longestLine)
for (line <- lines) {
val numSpaces = maxWidth - widthOfLength(line)
val padding = " " * numSpaces
println(padding + line.length + " | " + line)
}
}
else
Console.err.println("Please enter filename")
运行如下: