Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Predicates [closed]

Tags:

scala

I'm new to Scala and I'm trying to figure out what predicates are and the correct way to used them. The information I found online is not very clear to me or it assumes previous knowledge of predicates. Can someone explain what they are and perhaps show a few examples of how to use them in Scala?

like image 677
user2300867 Avatar asked Oct 12 '16 23:10

user2300867


People also ask

What is a predicate in Scala?

A predicate is a function that returns a Boolean . For example, to check if an Integer is even we can define the function isEven . scala> def isEven(i: Int) = i % 2 == 0 isEven: (i: Int)Boolean.


1 Answers

A predicate is a function that returns a Boolean.

For example, to check if an Integer is even we can define the function isEven.

scala> def isEven(i: Int) = i % 2 == 0
isEven: (i: Int)Boolean

It behaves as you would expect.

scala> isEven(2)
res1: Boolean = true

So, you can then pass this into a function like filter that takes a function that returns a boolean. The type signature for this is p: (A) ⇒ Boolean) where p is short for predicate.

scala> List(1,2,3,4,5,6,7,8,9,10).filter(isEven)
res2: List[Int] = List(2, 4, 6, 8, 10)

See Scala School for some good reading.

like image 62
Brian Avatar answered Oct 21 '22 11:10

Brian