Scala forall example?

前端 未结 3 1585
灰色年华
灰色年华 2021-01-31 07:44

I tried Google search and could not find a decent forall example. What does it do? Why does it take a boolean function?

Please point me to a reference (exce

3条回答
  •  抹茶落季
    2021-01-31 08:26

    The forall method takes a function p that returns a Boolean. The semantics of forall says: return true if for every x in the collection, p(x) is true.

    So:

    List(1,2,3).forall(x => x < 3)
    

    means: true if 1, 2, and 3 are less than 3, false otherwise. In this case, it will evaluate to false since it is not the case all elements are less than 3: 3 is not less than 3.

    There is a similar method exists that returns true if there is at least one element x in the collection such that p(x) is true.

    So:

    List(1,2,3).exists(x => x < 3)
    

    means: true if at least one of 1, 2, and 3 is less than 3, false otherwise. In this case, it will evaluate to true since it is the case some element is less than 3: e.g. 1 is less than 3.

提交回复
热议问题