gpt4 book ai didi

匹配 Java 接口(interface)时的 Scala match/case 语句

转载 作者:行者123 更新时间:2023-12-01 09:36:58 24 4
gpt4 key购买 nike

我正在使用 Scala match/case用于匹配给定 java 类的接口(interface)的语句。我希望能够检查一个类是否实现了接口(interface)的组合。我似乎可以让它工作的唯一方法是使用嵌套 match/case看起来丑陋的陈述。

假设我有一个实现 Person、Manager 和 Investor 的 PersonImpl 对象。我想看看 PersonImpl 是否同时实现了 Manager 和 Investor。我应该能够做到以下几点:

person match {
case person: (Manager, Investor) =>
// do something, the person is both a manager and an investor
case person: Manager =>
// do something, the person is only a manager
case person: Investor =>
// do something, the person is only an investor
case _ =>
// person is neither, error out.
}
case person: (Manager, Investor)只是行不通。为了让它工作,我必须做以下看起来很难看的事情。
person match {
case person: Manager = {
person match {
case person: Investor =>
// do something, the person is both a manager and investor
case _ =>
// do something, the person is only a manager
}
case person: Investor =>
// do something, the person is only an investor.
case _ =>
// person is neither, error out.
}

这简直丑陋。有什么建议么?

最佳答案

试试这个:

case person: Manager with Investor => // ...
with用于您可能想要表达类型交集的其他场景,例如在类型绑定(bind)中:
def processGenericManagerInvestor[T <: Manager with Investor](person: T): T  = // ...

顺便说一句—— 并不是说这是推荐的做法 , 但是——你也可以这样测试它: if (person.isInstanceOf[Manager] && person.isInstanceOf[Investor]) ... .

编辑:这对我很有效:
trait A
trait B
class C

def printInfo(a: Any) = println(a match {
case _: A with B => "A with B"
case _: A => "A"
case _: B => "B"
case _ => "unknown"
})

def main(args: Array[String]) {
printInfo(new C) // prints unknown
printInfo(new C with A) // prints A
printInfo(new C with B) // prints B
printInfo(new C with A with B) // prints A with B
printInfo(new C with B with A) // prints A with B
}

关于匹配 Java 接口(interface)时的 Scala match/case 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5859319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com