azy*_*oot 5 scala partialfunction
我对Scala很新,但我已经爱上了它.我已经阅读了有关部分功能的教程和文章.我想要实现的是让一个对象扩展PartialFunction [...,...]并直接用case定义它,而不需要定义isDefinedAt和apply方法.
例如
val partialfuncval : PartialFunction[Int,Boolean] = {
case 1 => false
}
Run Code Online (Sandbox Code Playgroud)
是部分函数的有效定义.但为什么我不能写
object PartialFunctionClass extends PartialFunction[Int,Boolean] {
case 1 => false
}
Run Code Online (Sandbox Code Playgroud)
?这将取消定义isDefinedAt和apply的需要,并且会使得编写某些类的类(由我正在使用的lib预定义)类型更容易.
这些选项中的一个是否足够你?
选项1
abstract class DelegatingPartialFunction[-T,+R](underlying: PartialFunction[T,R]) extends PartialFunction[T,R] {
def apply(t: T) = underlying.apply(t)
def isDefinedAt(t: T) = underlying.isDefinedAt(t)
}
Run Code Online (Sandbox Code Playgroud)
然后:
object PartialFunctionClass extends DelegatingPartialFunction[Int,Boolean]({
case 1 => false
})
Run Code Online (Sandbox Code Playgroud)
选项2
trait DelegatingPartialFunction[-T,+R] extends PartialFunction[T,R] {
val underlying: PartialFunction[T,R]
def apply(t: T) = underlying.apply(t)
def isDefinedAt(t: T) = underlying.isDefinedAt(t)
}
Run Code Online (Sandbox Code Playgroud)
然后:
object PartialFunctionClass extends DelegatingPartialFunction[Int,Boolean] {
val underlying = {
case 1 => true
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
675 次 |
| 最近记录: |