1

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.

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. What about the more complex scenarios? Is it possible to use pattern matching?
In this case pattern matching does not make sense, but if you match directly on integers, the compiler can create a switch/case statement.
0

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   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.