《scala cookBook》Chapter1

C:\Users\enmonster>f:  //进入cmd,进入盘f

F:\>cd scala
F:\scala>cd prog-scala-2nd-ed-code-examples//依次进入到所需目录

F:\scala\prog-scala-2nd-ed-code-examples>sbt//执行sbt命令
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0
[info] Loading global plugins from C:\Users\enmonster\.sbt\0.13\plugins
[info] Loading project definition from F:\scala\prog-scala-2nd-ed-code-examples\project
[info] Set current project to Programming Scala, Second Edition - Code examples (in build file:/F:/scala/prog-scala-2nd-ed-code-examples/)
> console//进入控制台(scala)
[info] Starting scala interpreter...
[info]
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_161).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val list = 1 +: 2//需要指定结束符Nil   +:方法不属于Int范围
<console>:10: error: value +: is not a member of Int
       val list = 1 +: 2
                    ^

scala> val list = 1 +: 2 +: Nil//正确的构造顺序
list: List[Int] = List(1, 2)

scala> val list = 1 +: Nil
list: List[Int] = List(1)

scala> val list = 1//这就不是List,而只是一个普通的Int
list: Int = 1

scala> val list =  Nil//直接用Nil声明一个空List,
list: scala.collection.immutable.Nil.type = List()

scala> case class With[A,B](a:A,b:B)//定义一个样板类
defined class With

scala> val with1 : With[String,Int] = With("Foo",1)//定义变量with1
with1: With[String,Int] = With(Foo,1)

scala> val with2 : With[String,Int] = With("Bar",2)//定义变量with2
with2: With[String,Int] = With(Bar,2)

scala> Seq(with1,with2) foreach { w =>//注意这里并没有.号去调用foreach,而是直接foreach
     | w match{//模式匹配
     | case s With i => println(s"$s with $i")//不明白!
     | case _ =>println(s"Unknownm :$w")
     | }
     | }
Foo with 1
Bar with 2

scala> Seq(with1,with2) foreach { w =>
     | w match{
     | case With[s,i] => println(s"$s with $i")//使用不规范,报错。应该用With(_,_)
     | case unexpected => println(s"$unexpected Unknown")
     | }
     | }
<console>:17: error: pattern must be a value: With[s,i]
Note: if you intended to match against the class, try `case With(_,_)`
       case With[s,i] => println(s"$s with $i")
                ^
<console>:17: error: not found: value s
       case With[s,i] => println(s"$s with $i")
                                    ^                                    
<console>:17: error: not found: value i
       case With[s,i] => println(s"$s with $i")
                                            ^

scala> Seq(with1,with2) foreach{//修改之后的样子
     |       w => w match{
     |       case With(s,i) => println(s"$s with $i")//注意这里的是With(s,i)
     |       case unknown => println(s"unknown")
     |       }
     |       }

Foo with 1//输出
Bar with 2


scala> val nonEmptyList = List(1,2,3,4,5)//List
nonEmptyList: List[Int] = List(1, 2, 3, 4, 5)

scala> val nonEmptyVector = Vector(1,2,3,4,5)//Vector
nonEmptyVector: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4, 5)

scala> val noEmptyMap = Map("one"->1)//Map
noEmptyMap: scala.collection.immutable.Map[String,Int] = Map(one -> 1)

scala> val s2 = ("one",1) +:("two",2) +: ("three",3) +: Nil//一个(String,Int)作为一个List的元素
s2: List[(String, Int)] = List((one,1), (two,2), (three,3))

scala> val str = "hello"
str: String = hello

scala> "hello".getClass .getName//直接对字符串"hello"操作
res2: String = java.lang.String

scala> val foo="""This is//使用三个"来存储多行字符
     |    a multiline
     | string"""
foo: String =
This is
   a multiline
string

scala> println(foo)
This is
   a multiline
string

scala> val foo="""This is
     |    a multiline
     | string""".stripMargin
foo: String =
This is
   a multiline
string

scala> println(foo)
This is
   a multiline
string

scala> "hello world".split(" ")
<console>:1: error: illegal character '\uff09'
"hello world".split(" "//错误的原因在于使用了中文的括号
                       ^

scala> "hello world".split(" ")
res8: Array[String] = Array(hello, world)//直接转换成了Array[String]

scala> val s1 = "eggs,milk,butter, Coco Puffs"
s1: String = eggs,milk,butter, Coco Puffs

scala> s1.split(",")
res10: Array[String] = Array(eggs, milk, butter, " Coco Puffs")//注意引号

scala> val s = "eggs, milk, butter, Coco Puffs"
s: String = eggs, milk, butter, Coco Puffs

scala> s.split(",").map(_.trim)
res11: Array[String] = Array(eggs, milk, butter, Coco Puffs)//再看看是否还有引号

scala> val upper = "hello,world".map(_.toUpper)//map操作,转为大写
upper: String = HELLO,WORLD

scala> val upper = for(c <- "hello world") yield c.toUpper//for-yield表达式,相当于map操作
upper: String = HELLO WORLD

scala> val res0 = s.foreach(println)
e
g
....
P
u
f
f
s

scala> val res0 = s.foreach(print)
eggs, milk, butter, Coco Puffs
scala> res0

scala> def toLower (c:Char): Char=(c.toByte+32).toChar//定义toLower方法
toLower: (c: Char)Char

scala> val res0 = "Hello".map(toLower)//因为存在小写字母,所以出现了“不正常”字符
res0: String = h????

scala> val res0 = "HELLO".map(toLower)
res0: String = hello

scala> val toLower = (c:Char) => (c.toByte+32).toChar
toLower: Char => Char = <function1>//定义toLower函数。同上面的toLower进行比较

scala> val res0 = "HELLO".map(toLower)
res0: String = hello

scala> val res0 = "HELLO".map(toLower)
res0: String = hello

scala> "Hello".map((_.toByte+32).toChar)
<console>:12: error: missing parameter type for expanded function ((x$1) => x$1.toByte.$plus(32))//缺少参数类型
       "Hello".map((_.toByte+32).toChar)

scala> "Hello".map(x => (x.toByte+32).toChar)//直接使用显式的变量即可
res15: String = h????//因为小写再转换就出错

scala> val numPatter = "[0-9]+".r//操作".r"将一串字符转换成正则表达式
numPatter: scala.util.matching.Regex = [0-9]+

scala> val address = "123 Main Street Suite 101"
address: String = 123 Main Street Suite 101

scala> val match1 = numPatter.findFirstIn(address)//样式numPatter在字符串address中首次出现所展示的内容
match1: Option[String] = Some(123)//返回值是一个Some()类型

scala> val match1 = numPatter.findAllIn(address)//找出所有匹配的内容
match1: scala.util.matching.Regex.MatchIterator = non-empty iterator//结果是非空的iterator

scala> match1.foreach(println)//遍历输出可得具体内容
123
101

scala> val match2 = numPatter.findAllIn(address).toArray//将结果转换为数组
match2: Array[String] = Array(123, 101)

scala> val match2 = numPatter.findAllIn(address).toList//将结果转换成List
match2: List[String] = List(123, 101)

scala> val match2 = numPatter.findAllIn(address).toVector//将结果转换成Vector
match2: Vector[String] = Vector(123, 101)

scala> import scala.util.matching.Regex//导入[Regex包]正则表达式的包
import scala.util.matching.Regex

scala> val numPattern2 = new Regex("[0-9]+")//直接使用Regex类来初始化一个正则表达式的样式numPattern2
numPattern2: scala.util.matching.Regex = [0-9]+

scala> val match3 = numPattern2.findFirstIn(address)
match3: Option[String] = Some(123)

scala> match3 match{
     | case Some(s) => println(s"Found :$s")
     | case None => println("Not Found")
     | }
Found :123

scala> val numPattern = "[0-9]+".r
numPattern: scala.util.matching.Regex = [0-9]+

scala> val res0 = numPattern.findAllIn(address)
res0: scala.util.matching.Regex.MatchIterator = non-empty iterator

scala> res0.foreach(x => x match{
     | case Some(s) => println(s"Found $s")
     | case None => println("Not Found")
     | }
     | )
<console>:17: error: constructor cannot be instantiated to expected type;
 found   : Some[A]//这个为啥会出现类型转换失败的错误?
 required: String
       case Some(s) => println(s"Found $s")
            ^
<console>:18: error: pattern type is incompatible with expected type;
 found   : None.type
 required: String
       case None => println("Not Found")
            ^

scala> "hello"(1)//直接应用下标
res23: Char = e

scala> "hello".apply(1)//apply方法,相当于求下标
res24: Char = e

scala> implicit class StringImprovements(s:String){//定义一个隐式转换!
     | def increment = s.map(c=>(c+1).toChar)
     | }
defined class StringImprovements

scala> val result = "HAL".increment//将这个隐式转换应用到"HAL"上
result: String = IBM

2.详细注解

  • 01.楼上的代码中有以下模式匹配,但是对s With i不是太懂
    scala> Seq(with1,with2) foreach { w =>//注意这里并没有.号去调用foreach,而是直接foreach
    | w match{//模式匹配
    | case s With i => println(s"$s with $i")//不明白!【待理解】
    | case _ =>println(s"Unknownm :$w")
    | }
    | }
  • 02.scala中Nil是什么?可以暂时将Nil理解成List中的结尾元素