Reputation: 10419
I am trying to write a function that returns a function based on the input parameter.
def myFunction(x: Int): x => Boolean {
x => if (x < 7) false
if (x % 2 == 0) false
else true
}
So if x is less than 7 or even false will be returned. Otherwise true is.
How do I write this using pattern matching?
And if it pointless to use pattern matching for Ints, what about something more complex like a list of Ints.
def myFunction(myList: List[Int]): x => Boolean {
// just doing something simple here real life is more complex.
x => if (myList.size() < 7) false
else true
}
Thanks.
Upvotes: 1
Views: 129
Reputation: 5962
I usually pattern match like this. Any expression returns a value - if else and matching should have approximately the same result.
x match{
case x if x < 7 => false
case x if (x % 2 == 0) => false
case _ => true }
Upvotes: 0
Reputation: 22171
Pattern matching is useless when dealing with primitive objects.
Other alternative would be :
Option(3).map(x => x < 7 || x % 2 == 0).getOrElse(false)
But for this simple case, I prefer simple if/else
.
For your second case, a function returning a partial function based on a List[Int]
would be:
def myFunction(myList: List[Int]): List[Int] => Boolean = {
case _ :: Nil if (myList.size < 7) => false
case _ => true
}
Upvotes: 1