Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create partial function from runtime value in Scala

Tags:

scala

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?

like image 861
sergeda Avatar asked Jun 10 '26 02:06

sergeda


1 Answers

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

  new Test(function.orElse{case `v` => true})
like image 92
Tim Avatar answered Jun 11 '26 21:06

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!