1.Tuple和List一样都是不可变对象(immutalbe),但是Tuple的元素可以是不同的类型
val myTuple = ("A", 1, "park", 3.13359 )
println(myTuple._1 ) // A
println(myTuple._2) // 1
println(myTuple._3) // park
创建Tuple只需把元素放在括号里面就可以了,上面创建了一个Tuple4类的实例,Tuple4在scala中的定义是这样的
/** A tuple of 4 elements; the canonical representation of a `scala`.`Product4`.
*
* @constructor Create a new tuple with 4 elements. Note that it is more idiomatic to create a Tuple4 via `(t1, t2, t3, t4)`
* @param _1 Element 1 of this Tuple4
* @param _2 Element 2 of this Tuple4
* @param _3 Element 3 of this Tuple4
* @param _4 Element 4 of this Tuple4
*/
@deprecatedInheritance("Tuples will be made final in a future version.", "2.11.0")
case class Tuple4[+T1, +T2, +T3, +T4](_1: T1, _2: T2, _3: T3, _4: T4)
extends Product4[T1, T2, T3, T4]
{
override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + ")"
}
类似5个元素的Tuple是Tuple5的实例,6个元素的Tuple是Tuple6的实例
因此就可以解释为什么会用 _1, _2, _3等来引用Tuple中的元素了
Tuple4定义中的类型参数前面有 + 号,这个代表 covarience参数,以后会深入讲解
2. Set有两类, 不可变的和可变的,名字相同,默认创建不可变的Set对象
var jetSet = Set("Bench", "Audi", "Tesilla")
jetSet += "LuHu"
println(jetSet.contains("Bicycle"))
To add a new element to a set, you call + on the set, passing in the new element. Both mutable and immutable sets offer a + method, but their behavior
differs. Whereas a mutable set will add the element to itself, an immutable
set will create and return a new set with the element added
对于immutable的Set ,+ 运算创建一个新的Set
对于mmutalbe的Set, +运算添加元素到它自己
3. Map与Set类似,也有immuatlbe和mutable两种实现
4. 读取文件
import scala.io.Source
object TestMain {
def main(args: Array[String]) {
var lines = Source.fromFile("E:/testRead.txt").getLines
lines.foreach(println)
}
}
转载于:https://blog.51cto.com/dingbo/1588843