接受Scala中参数的多种类型 [英] accept multiple types for a parameter in scala

查看:48
本文介绍了接受Scala中参数的多种类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象,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)
}

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

这篇关于接受Scala中参数的多种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆