的里氏替换原则状态'PartialFunction extends Function`是否违反LSP?
if
S
is a subtype ofT
, then objects of typeT
may be replaced with objects of typeS
without altering any of the desirable properties of that program.
然而,在Scala中,存在PartialFunction
是不适用/在所有情况下所定义。
trait Function1 {
def apply(x: A): R
}
trait PartialFunction extends Function1 {
def apply(x: A): R
def isDefinedAt(x: A): Boolean
}
如果应用PartialFunction
为不确定的值,你会收到一个异常。
在scala中创建PartialFunction
的一种简便方法是使用模式匹配。这样做,您会收到一个MatchError
未定义的值。
val fn:Function1[String, Int] = s => s.length
val pf:PartialFunction[String, Int] = {
case "one" => 3
}
def program(f:Function1[String, Int], s:String):(Boolean, Int) = (
f.isInstanceOf[Function1[String, Int]], f(s)
)
program(fn, "one") == program(pf, "one")
program(fn, "two") == program(pf, "two")
fn: String => Int = <function1>
pf: PartialFunction[String,Int] = <function1>
program: program[](val f: String => Int,val s: String) => (Boolean, Int)
res0: Boolean = true
scala.MatchError: two (of class java.lang.String)
at scala.PartialFunction$$anon$1.apply(delme.sc:249)
at scala.PartialFunction$$anon$1.apply(delme.sc:247)
at ...
两个fn
和pf
是Function1
亚型,但我不能代替通过pf
fn
不会改变我的program
。所以我认为这是对LSP的违反。
您认为如何?
这将主要是一个意见件。你有关于应用或使用更一般问题的更具体问题吗? – wheaties
绝对不是。我只是要求其他开发人员的建议。也许我应该将它发布到另一个社区? –
你也可以定义一个'Function1',它仅仅为''one'''以外的所有输入引发异常。你违反LSP的论点是抛出一个异常可能是一个不希望的改变,但是一个'Function1'仍然可以有输入来抛出异常。例如'的BigDecimal( “ABC”)'。 'PartialFunction'和'Function1'之间的主要区别在于你有一个内置的方法来检查元素是否被首先定义。 –