accept multiple types for a parameter in scala

泪湿孤枕 提交于 2019-12-06 19:07:51

问题


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
}

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?


回答1:


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)
}

Checkout http://www.scala-lang.org/api/current/scala/Either.html



来源:https://stackoverflow.com/questions/9611012/accept-multiple-types-for-a-parameter-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!