简体   繁体   English

Scala:在模式匹配中使用超类型运算符

[英]Scala: Using supertype operator in pattern matching

I have made my own framework of traits and classes that extend my traits. 我已经建立了自己的特征和类框架,以扩展我的特征。 The parent of all classes is a trait named 'Contract'. 所有类的父级都是名为“合同”的特征。 'Combinator' and 'ElementaryContract' are two immediate children of Contract. “ Combinator”和“ ElementaryContract”是Contract的两个直接子代。

def disintegrateContract[T](element: T): Elem = 
{

    element match
    {
      case com <: Combinator =>  matchCombinator(com)
      case e <:ElementaryContract =>matchElementaryContract(e)
    }
}

I want to make a match class that recognizes whether a passed 'Contract' is a subtype of 'Combinator' or 'ElementaryContract' and then pass it to some other functions. 我想创建一个匹配类,以识别传递的“合同”是“组合器”还是“基本合同”的子类型,然后将其传递给其他函数。 This is the compilation error I get: 这是我得到的编译错误:

 '=>' expected but '<:' found

Probably it does not recognize the subtype operator. 可能无法识别子类型运算符。 How can I make this happen? 我怎样才能做到这一点?

If understood you correctly the usual pattern matching should be fine -- if Bar extends Foo, it is Foo (plus something else): 如果正确理解,通常的模式匹配应该没问题-如果Bar扩展为Foo, 则为Foo (加上其他内容):

class SuperA
class ImplA extends SuperA

class SuperB
class ImplB extends SuperB

def disintegrateContract[T](element: T) = element match {
   case a: SuperA =>  println("I'm ancestor of Super A")
   case b: SuperB =>  println("I'm ancestor of Super B")
}

disintegrateContract(new ImplA)
// I'm ancestor of Super A
disintegrateContract(new ImplB)
// I'm ancestor of Super B

To have exact your situation there should be Super which SuperA and SuperB will extend, but it changes nothing. 要准确了解您的情况,应该有SuperA和SuperB可以扩展的Super,但是它什么也不会改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM