Programming in Scala (Second Edition) 读书笔记3

  1. 创建并初始化一个String Array

    val strArr1 = new Array[String](3)
    strArr1(0) = "How"
    strArr1(1) = "are"
    strArr1(2) = "you!"

上述代码被transform 为

    val strArr1 = new Array[String](3)
    strArr1.update(0, "How")
    strArr1.update(1, "are")
    strArr1.update(2, "you!")

scala doc 中有一下描述:

  /** Update the element at given index.
   *
   *  Indices start at `0`; `xs.update(i, x)` replaces the i^th^ elemen t in the array.
   *  Note the syntax `xs(i) = x` is a shorthand for `xs.update(i, x)`.
   *
   *  @param    i   the index
   *  @param    x   the value to be written at index `i`
   *  @throws       ArrayIndexOutOfBoundsException if `i < 0` or `length <= i`
   */
  def update(i: Int, x: T) { throw new Error() }

2.  使用伴随对象(companion object)创建并初始化Array

   

val strArr2 = Array("Fine", "thank", "you")

这里Array是一个对象的名字,在Scala中对象出现在函数的位置的时候,比如这里,对象后面跟了括号,scala的编译器就会自动寻找这个对象的apply方法,所以这里调用的其实是Array.apply

在scala 源码中可以看到

  // Array(e0, ..., en) is translated to { val a = new Array(3); a(i) = ei; a }
  def apply[T: ClassTag](xs: T*): Array[T] = {
    val array = new Array[T](xs.length)
    var i = 0
    for (x <- xs.iterator) { array(i) = x; i += 1 }
    array
  }

apply方法为我们创建了类Array的一个对象,并初始化。这里的object Array就是class Array的伴随对象。


3. 同理

    val strArr = Array("Fine", "thank", "you")
	println(strArr(0))  // strArr(0) 本质上调用的是 strArr.apply

4. 在Array 是可变类型, List是不可变类型。 List的使用示例

    val twoThree = List(2, 3)
    val oneTwoThree = 1 :: twoThree  // 这里 :: List的一个方法, 在Scala中所有的操作符(operator)都是方法,且以冒号结尾的操作符为右操作符(参数在左边,对象在右边) 
    println(oneTwoThree)  // List(1, 2, 3)

也可以这样

	  val oneTwoThree = 1 :: 2 :: 3 :: Nil
	  println(oneTwoThree) // List(1, 2, 3)


5. 为什么不往List的后面添加元素

Why not append to lists?

Class List does offer an “append” operation ―it’s written :+ and is

explained in Chapter 24― but this operation is rarely used, because

the time it takes to append to a list grows linearly with the size of the

list, whereas prepending with :: takes constant time. Your options if

you want to build a list efficiently by appending elements is to prepend

them, then when you’re done call reverse; or use a ListBuffer, a

mutable list that does offer an append operation, and when you’re done

call toList. 

追加元素的时间复杂程度会随元素个数线性增长

可以先向前追加,然后reverse

或先使用ListBuffer 再toList

    val L12345 = 1 :: 2 :: 3 :: 4 :: 5 :: Nil
    val L54321 = L12345.reverse
    print(L54321)  // List(5, 4, 3, 2, 1)
import scala.collection.mutable.ListBuffer

object TestMain {
  def main(args: Array[String]) {
    
    val lb = new ListBuffer[Int]
    lb.append(1)
    lb.append(2)
    lb.append(3)
    
    var l = lb.toList
    println(l)  // List(1, 2, 3)
  }
}


6.最后解释一下 val 和 var

  两者都是scala中的变量修饰符,如java中的static ,final。 

  val 的作用是正是声明一个final的变量,即不可再被赋值的变量

  var 与val相反

  另外scala中没有类似java 的static关键字


7.浏览一下List的其它方法

List() or Nil
The empty List
List("apple", "banana", "pare") create a new List[String]
"apple" :: "banana" :: "pear" :: Nil 同上
count(s => s.length == 4)
Counts the number of string elements that have length 4 
drop(2) Returns the list without its first 2 elements
dropRight(2) Returns the list without its rightmost 2 elements
exists(s => s=="until") Detemine whether a string element exists in the list
filter(s => s.length == 4) Return a list of all elements, in order, of the list that have lengh 4
forall(s => s.endWith("l")) Indiates whether all elements in  the list end with letter "l"
foreach(s => print(s))
Executes the print statement on each of the string in the list
foreach(print) Same as previous
head The first element
init a list of all but the last element
isEmpty Indicates whether the list is empty
last the last element
length number of elements
map(s => s + "y") Return a list resulting from adding a "y" to each string element in the list
mkString(", ") Makes a string with the elements of the list
remove(s => s.length==4) Return a list containning al elements of the list except those that have length 4
reverse Returns a list in reverse order
sort 
Return a list in alpabetical order
tail Returns the list minus its first element


你可能感兴趣的:(scala)