初识Scala
Scala是纯面对对象语言:every value is an object and every operation is a method call
For example, when you say 1 + 2 in Scala, you are actually invoking a method named + defined in class Int.

交互式Scala
使用 var 定义变量
|
|
交互式环境下的回退
多行代码情况下,scala左边会有竖杠表示代码仍在继续,如果发现代码有问题,可以按下两次回车开始新的命令
|
|
使用def定义函数
|
|
如果函数没有返回值,并且函数体可以简写为一行,那么可以如下简写:
|
|
没有返回值的函数,也就是函数返回void,在Scala中会被成为Unit类型
|
|
使用:q或者:quit退出交互式环境
|
|
初识循环
Scala不仅可以在交互环境运行,也可以以脚本运行,我们创建test.scala文件,并写入:
|
|
args为用户输入的参数列表,foreach语法的使用也很好理解
当我们执行:
|
|
将会看到一下输出:
|
|
上述方式中,Scala解释器能够根据args的元素基础类型猜出arg的类型,更明确表示类型的方式如下:
|
|
当然也有更简单的写法:
|
|
也可以使用for循环:
|
|
初识Array
Array是可变的,使用update方法对元素进行修改
|
|
初识List
与java中的List不同,Scala中的List是不可改变的
Scala使用:::进行List连接
|
|
将会输出:
|
|
::操作符在List前插入元素:
|
|
输出:
|
|
If a method is used in operator notation, such as a * b, the method is invoked on the left operand, as in a.*(b)—unless the method name ends in a colon. If the method name ends in a colon, the method is invoked on the right operand. Therefore, in 1 :: twoThree, the :: method is invoked on twoThree, passing in 1, like this: twoThree.::(1).
空List用Nil表示
初识元组
虽然元组和List一样,都是不可改变的,但是元组可以包含不同类型的元素:
|
|
The actual type of a tuple depends on the number of elements it contains and the types of those elements. Thus, the type of (99, "Luftballons") is Tuple2[Int, String]. The type of('u', 'r', "the", 1, 4, "me") is Tuple6[Char, Char, String, Int, Int, String]
注意元组中元素的索引方式
初识Set
Set有不可变的也有可变的,不导入包时,默认是不可变的Set
|
|
To add a new element to a set, you call + on the set, passing in the new element. On both mutable and immutable sets, the + method will create and return a new set with the element added. Although mutable sets offer an actual += method, immutable sets do not.

可变Set和不可变Set虽然叫同一个名字,但是属于不同的包
|
|
|
|
初识Map
Map与Set类似,有可变和不可变的,不导入包时,默认是不可变的Map
|
|
初识文件读取
|
|
重点
- Traits in Scala are like interfaces in Java, but they can also have method implementations and even fields.
- Scala中的数组使用
()索引,而不是[]
参考文档
- 《Programming in Scala, 3rd Edition》