快学scala笔记之01-数据类型

来源:互联网 发布:云房数据怎么样 编辑:程序博客网 时间:2024/05/16 10:47
1.3 数据类型
和Java一样, Scala也有7种数值类型: Byte 、Char 、Short 、Int 、Long 、Float和Double ,以及l个Boolean类型。跟Java不同的是,这些类型是类。

对象恒等比较
Scala的==和Java不同,scala 的==只用于比较两个对象的值是否相同。而对于引用类型的比较使用另外的操作符 eq 和 ne。
scala> val a = List(1,2,3)
a: List[Int] = List(1, 2, 3)
scala> val b = a
b: List[Int] = List(1, 2, 3)
scala> val c = List(1,2,3)
c: List[Int] = List(1, 2, 3)

scala> a==b
res7: Boolean = true
scala> a eq b
res8: Boolean = true
scala> a == c
res9: Boolean = true
scala> a eq c
res10: Boolean = false
scala> a ne c
res11: Boolean = true

Lift
Safer is to use lift so you can extract the value if it exists and fail gracefully if it does not.
This will return None if the list isn't long enough to provide that element, and Some(value) if it is.
scala>val l = List("a","b","c")scala> l.lift(1) //Some("b")scala> l.lift(5) //None

2. 10 过程
如果函数体包含在花括号当中但没有前面的=号,那么返回类型就是Unit。这样的函数被称做过程( procedure )。过程不返回值,我们调用它仅仅是为f 它的副作用。

由于过程不返回任何值, 所以我们可以略去=号。

2.11 懒值
当va1被声明为同时,它的初始化将被推迟,直到我们首次对它取值。
lazy val words = scala.io.Source.fromFil e( "/usr/share/dict/words" ) .mkString
如果程序从不访问words ,那么文件也不会被打开。

懒值对于开销较大的初始化语句而言十分有用。它们还可以应对其他初始化问题,比如循环依赖。更重要的是,它们是开发懒数据结构的基础。
你可以把懒值当做是介于val和de他包中间状态

// 在words被定义时即被取值
val words = scala.io.Source.fromFil e( "/usr/share/dict/words" ) .mkString
// 在words被首次使用时被取值
lazy val words = scala.io.Source.fromFil e( "/usr/share/dict/words" ) .mkString
// 在每一次words被使用时被取值
def words = scala.io.Source.fromFil e( "/usr/share/dict/words" ) .mkString

3 数组相关操作
若长度固定则使用Array ,若长度可能有变化则使用ArrayBuffer。
提供初始值时不要使用new。
用()采访问元素。
用for (elem <- arr)来遍历元素。
用for (elem <- arr if ...)... yield ...来将原数组转型为新数组。
Scala数组和Java数组可以互操作;用ArrayButfer ,使用scala.collection.JavaConversions
中的转换函数。
3.1 定长数组
val nums = new Array[Int] (10)

3.2 变长数组:数组缓冲
import scala.collection.mutable.ArrayBuffer
val b = ArrayBuffer[lnt]()
或者new ArrayBuffer [Int]
b +=1
b += (1 , 2, 3 , 5)
b ++= Array(8, 13, 21) // 用++=操作符迫加任何集合
b. trimEnd (5 )

b.insert(2, 6)
b.insert(2, 7, 8, 9)
b.remove (2)
b.remove(2, 3)

3.3 遍历数组和数组缓冲
0 until b.length // 等价于 0 until (b.length,1)
0 until (b.length,2)
0 until (b.length,2).reverse

3.4 数组转换
for ( ...) yield循环创建了一个类型与原始集合类型相同的新集合。
val a = Array(2, 3, 5, 7, 11)
val result = for (elem <- a) yield 2 * elem
// result是Array(4, 6, 10, 14, 22)

加过滤
for(elem <- a if elem % 2 == 0) yield 2*elem

函数式:
a.filter(_ % 2 == 0).map(_ * 2)
或者
a.filter { _ % 2 == 0 } map { _ * 2 }

给定一个整数的数组缓冲,我们想要移除除第一个负数之外的所有负数。
var first = true
var n = a.length
var i = 0
while(i < n) {
if( a(i) > 0) {
i += 1
} else {
if(first) { i+= 1}
else {
first = false
a.remove(i)
n -+ 1
}
}
}

更高效的方式:
var first = true
val indexes = for ( i <- 0 until a.length if first || a(i) >= 0 ) yield {
if ( a(i) < 0) first = false; i
}
for ( j <- 0 until idexes.length)
a(j) = a(indexes(j))
a.trimEnd(a.length - indexes.length)

3.5 常用算法
val b = ArrayBuffer(1, 7 , 2, 9 )
val bSorted = b.sorted(_ < _) // b没有被改变; bSorted是ArrayBuffer(1, 2, 7, 9)
可以直接对一个数组排序,但不能对数组缓冲排序:
val a = Array(1 , 7, 2, 9)
scala.util.Sorting.quickSort(a)
// a现在是Array(1, 2, 7, 9)

a .mkString( " and ")
// "1 and 2 and 7 and 9"
a .mkString ("<", "," , ">")
// " <1 , 2 , 7 , 9>"

3.7 多维数组
和Java一样,多维数组是通过数组的数组来实现的。用ofDim方法:
val matrix = Array.ofDim[ Double](3, 4) // 三行,四列 初始化为全0.0矩阵

4 映射和元组
4.1 构造映射
不可变:
val scores = Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8)
或者
val scores = Map(("Alice", 10), ("Bob", 3), ("Cindy", 8))

4.3 更新映射
可变:
val scores = new scala.collection.mutable.HashMap[String, Int]
scores( "Fred") = 7
scores += ( "Bob" -> 10, "Cindy" -> 8)
scores -= "Fred" //删除某个键和对应的值

你不能更新一个不可变的映射,但你可以做一些同样有用的操作一一获取一个包
含所需要的更新的新映射:
val newScores = scores + ("Bob" -> 11, "Fred" -> 7)
val newScores2 = newScores - "Fred"

4.4 迭代映射
for (k, v) <- map} 处理k和v
scores.keySet // 一个类似(Set ( "Bob", "Cindy", "Fred" , "Alice " ) 这样的集
for (v <- scores.values) println(v} //将打印10 8 7 10或其他排列组合
for (伙, v) <- 映射) yield (v, k) // 反转

4.5 已排序映射
按key排序:
val scores = scala.collection.immutable.SortedMap("Alice" -> 10, "Fred" -> 7, "Bob" -> 3, "Cindy" -> 8)
按插入顺序排序:
val months = scala.collection.mutable.LinkedHashMap( "January" -> 1, "February" -> 2, "Marcht" -> 3, "April" -> 4, "May" -> 5)

4.7 元组(Tuple)
不同类型的值的集合。和数组或字符串中的位置不同,元组的各组元从1开始,而不是0 。
val t = (1, 3.14 , "Fred")
val (first, _, third) = t
"New York".partition(_.isUpper) // 输出(String, String) = (NY,ew ork)


val simbols = Array ("<", "-", ">")
val counts = Array(2, 10, 2)
val pairs =simbols.zip(counts)
// pairs: Array[(String, Int)] = Array((<,2), (-,10), (>,2))
for ((s,n) <- pairs) Console.print(s*n)
// <<---------->>












0 0
原创粉丝点击