Scala if Statements and for Loop
scala 中的 if 和其它编程语言中不同的一点是 if 表达式的返回值。比如下面这样,
val configFilePath = if (configFile.exists()) { configFile.getAbsolutePath } else { configFile.createNewFile() configFile.getAbsolutePath }
configFilePath: String = /Applications/IntelliJ IDEA 15.app/Contents/bin/somefile.txt
一个基本的for循环语句,
val dogBreeds = List("Doberman", "Yorkshire Terrier", "Dachshund", "Scottish Terrier", "Great Dane", "Portuguese Water Dog") for (bread <- dogBreeds) println(bread)
表达式
bread <- dogBreeds
叫做generator expression,这样命名是因为它从一个集合里产生一个个体值。left arrow operator (<-) 是用来遍历一个集合的。比如下面这样,
for (i <- 1 to 10) println(i)
在for循环中,可以过滤数据,如下,
val dogBreeds = List("Doberman", "Yorkshire Terrier", "Dachshund", "Scottish Terrier", "Great Dane", "Portuguese Water Dog") for (bread <- dogBreeds if bread.contains("Terrier") ) println(bread)
还可以使用多个过滤条件,
for (bread <- dogBreeds if bread.contains("Terrier") if !bread.startsWith("Yorkshire") ) println(bread)
这两种方式是等价的,
for (bread <- dogBreeds if bread.contains("Terrier") && !bread.startsWith("Yorkshire") ) println(bread)
上面那段话的意义就是,for 循环中的 yield 会把当前的元素记下来,保存在集合中,循环结束后将返回该集合。Scala 中 for 循环是有返回值的。如果被循环的是 Map,返回的就是 Map,被循环的是 List,返回的就是 List,以此类推。
scala> val filteredBreeds = | for (breed <- dogBreeds | if breed.contains("Terrier") && !breed.startsWith("Yorkshire") | ) yield breed filteredBreeds: List[String] = List(Scottish Terrier) scala> scala> filteredBreeds.toString() res3: String = List(Scottish Terrier)
下面遍历Map,
scala> val map = Map("key1" -> "value1", "key2" -> "value2", "key3" -> "value3") map: scala.collection.immutable.Map[String,String] = Map(key1 -> value1, key2 -> value2, key3 -> value3) scala> val temp_map = for (m <- map | if m._1.equals("key1") | ) yield m temp_map: scala.collection.immutable.Map[String,String] = Map(key1 -> value1) scala> temp_map.toString() res4: String = Map(key1 -> value1)
=============END=============