我正在尝试从运行时值创建部分函数,然后像这样组合部分函数:
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))
这段代码打印
true
true
true
但最后一行应该是错误的。 为什么会这样?我做错了什么?
最佳答案
{ case v => true }
始终匹配。你想测试 v
的值:
new Test(function.orElse{case `v` => true})
关于scala - 如何在 Scala 中从运行时值创建偏函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60771970/