How to create partial function from runtime value in Scala

Viewed 47

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 Answers

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

  new Test(function.orElse{case `v` => true})
Related