3

I'm trying to create partial function from runtime value and combine partial functions after that like this:

class Test(val function: PartialFunction[Int, Boolean]) {
  def add(v: Int): Test = {
    new Test(function.orElse{case v => true})
  }
  def contains(v: Int) = function.isDefinedAt(v)
}

val test: Test = new Test({case 1 => true})
val test2 = test.add(2)
println(test2.contains(1))
println(test2.contains(2))
println(test2.contains(3))

This code prints

true
true
true

But the last line should be false. Why is this so? What I'm doing wrong?

1 Answer 1

5

{ case v => true } is always a match. You want to test the value of v:

  new Test(function.orElse{case `v` => true})
Sign up to request clarification or add additional context in comments.

2 Comments

Can you, please, provide more info about cases when isDefinedAt can return true even if the function will fail?
I have re-checked the documentation and I was wrong about this. isDefinedAt does accurately indicate whether a value is handled by the partial function or not. So your code is good to go, and apologies for confusing things.

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.