如何解决Scala:两个不同类的实例,相同的方法
| 这是一个琐碎的问题,我只是想知道我是否可以在这里使用Scala式的东西。我有2个不同的类(Server1
和Server2
)都实现了相同的接口/特性(使用方法.A()
和.B()
)。
这显然会使编译器感到困惑:
var server = null
if(cond) server=new Server1 else server=new Server2
server.A() //or server.B()
我主要是好奇是否可以使用Scala的Option巧妙地解决这个问题。谢谢。
解决方法
可以随时添加类型注释:
var server: TraitOrInterface = null
但是,由于vars有点怪异...
val server = if (cond) {
new Server1()
} else {
new Server2()
}
在第二个示例中,Scala应该能够统一类型。 (我相当肯定,在某些情况下它无法统一-或在某些情况下无法完全统一,但是请先尝试一下,然后再键入类型注释,可以按第一个示例添加)
REPL演示:
class X
trait Y
class A extends X with Y {}
class B extends X with Y {}
val uni = if (true) new A() else new B()
uni
>> res3: X with Y = A@17b8cf0
快乐的编码。
结构类型示例中,example8ѭ别名是为了方便起见,但在技术上不是必需的。
class Cat { def speak() = \"meow\" }
class Dog { def speak() = \"woof\" }
type ThingThatSpeaks = { def speak(): String }
val speaker : ThingThatSpeaks = if (true /* smart */) new Cat() else new Dog()
speaker
>> res4: ThingThatSpeaks = Cat@2893fc
speaker.speak()
>> res5: String = meow
请注意,类型注释是必需的,否则...
val speaker = if (true /* smart */) new Cat() else new Dog()
speaker
>> res6: ScalaObject = Cat@f0ac6e
speaker.speak()
>> error: value speak is not a member of ScalaObject
, 不是Option
,而是Either
:
var server = if (cond) Right(new Server1) else Left(new Server2)
server match {
case Right(srv) => srv.A()
case Left(srv) => srv.B()
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。