Scala 当ojbect ref更新时,新ref中的方法是否可以访问?
在下面的代码中,我正在将引用t从类型t更新为类型S。当我更新引用时,我是否应该不能访问类型S上的方法?在下面的代码Scala 当ojbect ref更新时,新ref中的方法是否可以访问?,scala,Scala,在下面的代码中,我正在将引用t从类型t更新为类型S。当我更新引用时,我是否应该不能访问类型S上的方法?在下面的代码t中,printS不编译 object liskov { //if S is a subtype of T, then objects //of type T may be replaced with objects of type S class T { def printT() { println("T") } } c
t中,printS
不编译
object liskov {
//if S is a subtype of T, then objects
//of type T may be replaced with objects of type S
class T {
def printT() {
println("T")
}
}
class S extends T {
def printS() {
println("S")
}
}
var t: T = new T //> t : liskov.T = liskov$T@1e152c5
var s: S = new S //> s : liskov.S = liskov$S@80d1ff
println(t) //> liskov$T@1e152c5
t = s
println(t) //> liskov$S@80d1ff
s.printS //> S
t.printS
}
正如那些评论的人所说,只有静态类型的
var t:t
可以访问t
的成员。但是,您可以轻松地进行动态类型查询,以将T
的实例与其子类型的实例区分开来:
t match {
case s: S => /* here, s h as static type S and so printS is available */
case _: => /* here only the T's members are available (via t) */
}
是的,当你现在更新所有你看到的引用时-它是一个T而不是一个s(这就是LSP的全部要点,对于T用户来说,事实上你的T实际上是一个s是不相关的,他们可以在行为上将它用作一个T).@Benjamin Gruenbaum所以即使t指向类型S,类型S上的方法也不能从t调用?假设你有一个接受t的方法,现在你将它传递给S。如果它可以调用S的方法,它可以对任何传递的t这样做,因为你事先不知道它们实际上是Ss,当你传递一个事实上不是S的T时会发生什么?这将调用对象上不存在的方法。