简体   繁体   English

如何在Scala中对多个类型进行模式匹配?

[英]How to pattern match multiple types in Scala?

How to perform pattern matching for multiple types in scala ? 如何在Scala中对多种类型执行模式匹配?

I am looking to achieve something like below where pattern match type of a and b and execute the code for the combination of type. 我希望实现以下类似的模式,其中模式匹配a和b的类型,并执行类型组合的代码。

def equals[T](a: T, b: T) = {
    (a,b) match {
        case (a,b) : (String, String) = isEquals(a.asInstanceOf[String],b.asInstanceOf[String])
        case (a,b) : (Int, Int) = isEquals(a.asInstanceOf[Int],b.asInstanceOf[Int])  
    }
}

You were very close: 您非常接近:

def equals[T](a: T, b: T) =
  (a, b) match {
    case (a: String, b: String) => println(s"Strings: $a $b")
    case (a: Int, b: Int)       => println(s"Ints: $a $b")
    case _                      => println("Not sure what")
  }

equals("foo", "bar") // Strings: foo bar
equals(12, 34)       // Ints: 12 34
equals(true, false)  // Not sure what

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

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