接受Scala中参数的多种类型

编程入门 行业动态 更新时间:2024-10-15 02:26:16
本文介绍了接受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) }

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

更多推荐

接受Scala中参数的多种类型

本文发布于:2023-07-14 10:11:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1104067.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多种   参数   类型   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!