我有两个对象,ObjectA 和 ObjectB,它们都有一个方法 update().我想编写一个接受 ObjectA 或 ObjectB(但不接受其他类型)的函数.从概念上讲,这就是我想要做的:
I have two objects, ObjectA and ObjectB, both with a method update(). I want to write a function that accepts either ObjectA or ObjectB (but no other types). Conceptually, this is what I am trying to do:
def doSomething[T <: ObjectA | T <: ObjectB](obj: T) = { obj.update }我意识到还有其他方法可以解决这个问题(例如,update() 方法的结构类型、公共基类等)但我的问题是在 Scala 中可以这样做,如果是这样,那是什么语法?这叫什么?
I realize there are other ways to solve this problem (eg, structural typing of the update() method, common base class, etc) but my question is it is possible to do it this way in Scala and if so what is the syntax? And what is this called?
推荐答案在 Scala 中,有一个类型Either"来创建不相交的联合.基本上,您将执行以下操作:
In Scala, there is the type Either to make a disjoint union. Basically, you will do something like:
def doSomething(obj: Either[ObjectA, ObjectB]) { obj.fold(fa, fb) }结帐 www.scala-lang/api/current/scala/Either.html
更多推荐
接受Scala中参数的多种类型
发布评论