1

I am expecting my partial function to discard for input 0 , but instead it is giving match error . Will you please explain exactly why is it happening? What I am missing? enter image description here

object PartialFunction extends App {

  val divider : PartialFunction[Int,Int] = {
    case d : Int if d != 0 => 42/d
  }
  println(divider(0))
  //println(fraction(0))
}
2
  • 1
    because it can't match any of your patterns? Commented Jan 11, 2017 at 14:17
  • 1
    What is your expected output? How could the compiler know what to do with that divider(0) call? You should wrap it with a if (divider.isDefinedAt(0)) Commented Jan 11, 2017 at 14:22

2 Answers 2

3

You did not tell what to do when the input is 0. 0 does not match the case where because of the guard d != 0

Change your implementation to accommodate 0 case

  val divider : PartialFunction[Int,Int] = {
    case d : Int if d != 0 => 42/d
    case 0 => 0 //return some integer
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you , I was thinking as case is matching for any integer , why it shows match error for 0 , but yeah now I am pretty clear , it's guard which is preventing to evaluate 0, so it's kind of nomatch for 0 .
1

Or you can define what's the default case.

val divider : PartialFunction[Int,Int] = {
    case d : Int if d != 0 => 42/d
    case _ => 0
  }

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.