Scala Cookbook 摘录

Scala Cookbook》,感谢XX提供的电子书!

(链接可下载,仅供学习)(迁进 K8S 暂时挂掉了。。有空再补)

P.S. 有本书确实很有用。。

Reading record

Read till …

  • chapter 1.4 Substituting Variables into Strings, June.11th, 14:33

Notes

Page 2, 引号的区别

敲了两行发现不一样:

1
2
3
4
5
scala> val result = hello.filter(_ !="l")
result: String = hello, world!

scala> val result = hello.filter(_ !='l')
result: String = heo, word!

answer: scala中单引号表示char,双引号表示string,三引号可以跨行。

Page 9, if you call split with a Char argument instead of a String argument, you’re using the split method from StringLike:

1
2
3
4
5
6
7
// split with a String argument
scala> "hello world".split(" ")
res0: Array[java.lang.String] = Array(hello, world)

// split with a Char argument
scala> "hello world".split(' ')
res1: Array[String] = Array(hello, world)

Page 5, == method

A pleasant benefit of the == method is that it doesn’t throw a NullPointerException on a basic test if a String is null:

1
2
3
4
5
6
7
scala> val s4: String = null
s4: String = null

scala> s3 == s4
res2: Boolean = false
scala> s4 == s3
res3: Boolean = false

However, be aware that calling a method on a null string can throw a NullPointerException:

1
2
3
4
5
6
scala> val str: String = null
str: String = null

scala> str.toUpperCase
java.lang.NullPointerException
... 33 elided

Page 11, \n in String

1
2
3
4
5
6
7
8
9
10
11
12
13
scala> s"foo\nbar"
res4: String =
foo
bar

scala> s"foobar"
res5: String = foobar

scala> raw"foo\nbar"
res7: String = foo\nbar

scala> raw"foobar"
res8: String = foobar

Why it has a new line in the first command s"foo\nbar"?

Page 14, for/yield

基本用法:把for循环里面想要的值存为一个collection

1
2
3
4
5
scala> val hello = "hello, world!".map(c => c.toUpper)
hello: String = HELLO, WORLD!

scala> val hello = for (c <- "hello, world!") yield c.toUpper
hello: String = HELLO, WORLD!

继续有意思的:

1
2
3
4
5
scala> val result = for {
| c <- "hello, world"
| if c != 'l'
| } yield c.toUpper
result: String = HEO, WORD

Page 15, map

1
2
3
4
5
6
7
// first example
"HELLO".map(c => (c.toByte+32).toChar)

// second example
"HELLO".map{ c =>
(c.toByte+32).toChar
}

The 1st example use “()” in one line, and the 2nd use “{}” for multi lines. 一次处理String里面的一个char。

Pg 217, CHAPTER 9 Functional Programming

Page 241, collect

For instance, the divide function shown earlier is a partial function that is not defined at the Int value zero. Here’s that function again:

1
2
3
val divide: PartialFunction[Int, Int] = {
case d: Int if d != 0 => 42 / d
}

If you attempt to use this function with the map method, it will explode with a MatchError:

1
2
3
scala> List(0,1,2) map { divide }
scala.MatchError: 0 (of class java.lang.Integer)
stack trace continues ...

However, if you use the same function with the collect method, it works fine:

1
2
scala> List(0,1,2) collect { divide }
res0: List[Int] = List(42, 21)

This is because the collect method is written to test the isDefinedAt method for each element it’s given. As a result, it doesn’t run the divide algorithm when the input value is 0 (but does run it for every other element). You can see the collect method work in other situations, such as passing it a List that contains a mix of data types, with a function that works only with Int values:

1
2
scala> List(42, "cat") collect { case i: Int => i + 1 }
res0: List[Int] = List(43)

Because it checks the isDefinedAt method under the covers, collect can handle the fact that your anonymous function can’t work with a String as input.

Pg 245, CHAPTER 10 Collections

Page 279, for/yield

见了很多,也用了不少,系统地学习一下。

Chapter 10.13. Transforming One Collection to Another with for/yield

create a new collection from an existing collection by transforming the elements with an algorithm

Page 282, map

Chapter 10.14. Transforming One Collection to Another with map

transform one collection into another by applying an algorithm to every element in the original collection

Page 298, foldLeft

Chapter 10.20 Walking Through a Collection with the reduce and fold Methods

1
2
c foldLeft(z)(op)
// Applies the operation to successive elements, going from left to right, starting at element z.

要用到 foldLeft,不认识,源码注释看不明白,网上解释浮于表面。翻了一圈书,书里是先从 reduceLeft 讲起。

For example, use reduceLeft to walk through a sequence from left to right (from the first element to the last). reduceLeft starts by comparing the first two elements in the collection with your algorithm, and returns a result. That result is compared with the third element, and that comparison yields a new result. That result is compared to the fourth element to yield a new result, and so on.

就是对一个序列,从左到右(从第一个到最后一个)依次取出来比较,1和2比较的结果继续和3比,再得出一个结果,然后1和2比较的结果继续和3比的结果继续和4比,最后得出一个最后的结果,返回。

然后就很好理解 foldLeft 了,就是在 reduceLeft 的序列的最左边再加上一个传入的 “seed”,也就是再加上“第 0 个元素”,然后再接着两两比较。

剩下的 reduceRightfoldRight,自然就是从遍历了~

类似的还有 scanLeftscanRight,这里不说了。

Page 411, CHAPTER 13 Actors and Concurrency

Link to new post Actors and Concurrency in Scala.

Tips in the book

  • Page 3, When first learning Scala, take a look at the source code for the Predef object. It provides nice examples of many Scala programming features.
  • Page 6, In idiomatic Scala, you never use null values. The discussion in this recipe is intended to help you understand how == works if you en‐counter a null value, presumably from working with a Java library, or some other library where null values were used. If you’re coming from a language like Java, any time you feel like using a null, use an Option instead. (I find it helpful to imagine that Scala doesn’t even have a null keyword.) See Recipe 20.6, “Using the Option/Some/None Pattern”, for more information and examples.
  • Page 11, The most common printf format specifiers are shown in Table 1-1 in the Discussion.
  • Page 15, Wikipedia describes imperative programming like this: Imperative programming is a programming paradigm that describes computation in terms of statements that change a program state … imperative programs define sequences of commands for the computer to perform. This is shown in the Java example, which defines a series of explicit statements that tell a computer how to achieve a desired result.

Traps from the book

深得我心!博主晚餐加鸡腿!