Scala Collections集合的几个重要概念

几个重要的概念

谓词是什么(What a predicate is)

A predicate is simply a method, function, or anonymous function that takes one or more parameters and returns a Boolean value. For instance, the following method returns true or false, so it’s a predicate:

def isEven (i: Int) = if (i % 2 == 0) true else false

谓词就是一个方法,一个函数、一个匿名函数
接受一个或者多个参数,返回一个Boolean值,如上面这个函数啊的返回值就是true或者false,所以它是一个谓词

匿名函数是什么( What an anonymous function is):

The concept of an anonymous function is also important. here’s an example of the long form for an anonymous function:

(i: Int) => i % 2 == 0

Here’s the short form of the same function:

_ % 2 == 0

匿名函数是一个很重要的概念,上面第一段代码一个完整的匿名函数的例子,下面一个简化版的例子,他们看起来并不像,但当在集合里用到filter方法时,这种简短的代码会非常强大

scala> val list = List.range(1, 10)
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> val events = list.filter(_ % 2 == 0) 
events: List[Int] = List(2, 4, 6, 8)

隐式循环( Implied loops)

This is a nice lead-in into the third topic: implied loops. As you can see from that example, the filter method contains a loop that applies your function to every element in the collection and returns a new collection. You could live without the filter method and write equivalent code like this:
这里引入了隐式循环。如上例中所见filter方法包含了一个循环,会遍历集合里面的每个元素,然后返回一个新的集合,也可不用filter方法用下列代码实现这个功能

for {
    e <- list
    if e % 2 == 0 
   } yield e

But I think you’ll agree that the filter approach is both more concise and easier to read.
但是我想你也会同意filter这种方式既精简又易读
Collection methods like filter, foreach, map, reduceLeft, and many more have loops built into their algorithms. As a result, you’ll write far fewer loops when writing Scala code than with another language like Java.
像filter、foreach、map、reduceLeft和许多类似的集合方法都自带隐式循环。所以相比JAVA,Scala可以少写很多循环

你可能感兴趣的:(Scala Collections集合的几个重要概念)