scala学习笔记(2)

1 Loop 

(1) for (i <- 1 to 3){

# 1 2 3

}

(2) for (i <- 1 until 3){

#1 2

}

(3)过滤

for (i <- 1 to 10;

     if i != 3; if i < 8){

# 1 2 4 5 6 7

}

(4) yield

for 循环中的 yield 会把当前的元素记下来,保存在集合中,循环结束后将返回该集合。Scala 中 for 循环是有返回值的。如果被循环的是 Map,返回的就是  Map,被循环的是 List,返回的就是 List,以此类推。

基本语法

var retVal = for{ var x <- List
     if condition1; if condition2...
}yield x 

例子

scala> for (i <- 1 to 5) yield i * 2
res11: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10)

scala> val a = Array(1, 2, 3, 4, 5)
a: Array[Int] = Array(1, 2, 3, 4, 5)
scala> for (e <- a) yield e
res5: Array[Int] = Array(1, 2, 3, 4, 5)

for (i <- a if i % 2 == 0 if i > 6) yield i
res53: List[Int] = List(8)

  

object Test {
   def main(args: Array[String]) {
      var a = 0;
      val numList = List(1,2,3,4,5,6,7,8,9,10);
      // for loop execution with a yield
      var retVal = for{ a <- numList
                        if a != 3; if a < 8
                      }yield a
      // Now print returned values using another loop.
for( a <- retVal){
         println( "Value of a: " + a );
} }
}

(5) 多个for

for (i <- 1 to 3; j <- 4 to 6 if i != j) yield (i, j)
res5: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,4), (1,5), (1,6), (2,4), (2,5), (2,6), (3,4), (3,5), (3,6))  

2

在scala中,并不提供break或continue等语句,如果要跳出循环,有以下语句:
1. 使用一个布尔控制变量代替——while循环中
2. 使用return
3. 使用Breaks对象中的break方法:
import scala.util.control.Breaks._
breakable {
for (...) {
if (...) break; // Exits the breakable block
...
}
}

3 数组

val greetStrings = new Array[String](3)

//或者
val numNames = Array("zero", "one", "two")

scala> numNames(0) //提取数据不用[]而是用()
res54: String = zero

4 Option

  选项 Option
  Option 是一个表示有可能包含值的容器。

  Option基本的接口是这样的:

trait Option[T] {
def isDefined: Boolean
def get: T
def getOrElse(t: T): T
}

  Option本身是泛型的,并且有两个子类: Some[T] 或 None

  我们看一个使用Option的例子:

  Map.get 使用 Option 作为其返回值,表示这个方法也许不会返回你请求的值。

scala> val numbers = Map("one" -> 1, "two" -> 2)
numbers: scala.collection.immutable.Map[java.lang.String,Int] = Map(one -> 1, two -> 2)

scala> numbers.get("two")
res0: Option[Int] = Some(2)

scala> numbers.get("three")
res1: Option[Int] = None

  现在我们的数据似乎陷在Option中了,我们怎样获取这个数据呢?

  直觉上想到的可能是在isDefined方法上使用条件判断来处理。

// We want to multiply the number by two, otherwise return 0.
val result = if (res1.isDefined) {
res1.get * 2
} else {
0
}


  我们建议使用getOrElse或模式匹配处理这个结果。

val result = res1 match {
case Some(n) => n * 2
case None => 0
}

  getOrElse 让你轻松地定义一个默认值。

val result = res1.getOrElse(0) * 2

  模式匹配能自然地配合Option使用。

 

原文地址:https://www.cnblogs.com/yxzfscg/p/4898009.html