代码之家  ›  专栏  ›  技术社区  ›  Graham Savage

Scala模式多次匹配同一类型参数

  •  2
  • Graham Savage  · 技术社区  · 12 年前

    我希望模式匹配元组中的项,其中项具有相同的类型,包括类型参数。我的用例相当复杂,但我试图在这里提取一个最小的示例来说明问题:

    class Foo[T] { }
    
    val input = ( new Foo[String], new Foo[String] )
    
    input match {
      case (a:Foo[x], b:Foo[x]) =>
        // Do things that rely on a and b having exactly the same type
    }
    

    但这无法编译,因为我正在使用 x 在case语句中两次。编译时出现以下错误:

    error: x is already defined as type x
    

    我已经尝试过更改匹配,以拉出两个输入的不同类型参数,然后测试它们的相等性:

    input match {
      case (a:Foo[x], b:Foo[y]) if (x == y) =>
        // Do things that rely on a and b having exactly the same type
    }
    

    但它无法编译,导致错误

    error: not found: value x
    

    是否有一些Scala语法可以用来将两种类型匹配为相同的、未指定的类型?我正在运行Scala 2.9.2

    1 回复  |  直到 12 年前
        1
  •  1
  •   Travis Brown    12 年前

    当你发现自己在模式匹配中使用类型或类型变量时,你应该三思,第一是因为类型删除意味着它不可能工作,第二是因为参数化意味着不应该工作。几乎总是有更好的解决方案。

    在这种情况下,您可以执行以下操作:

    class Foo[T] { }
    
    val input = (new Foo[String], new Foo[String])
    
    def doSomething[A](pair: (Foo[A], Foo[A])) = ???
    

    现在 doSomething(input) 将编译,但 doSomething((new Foo[Char], new Foo[Int])) 不会(假设您将type参数保留为 Foo 不变)。老实说,这对项中的项仍然没有太多用处,因为您只知道它们具有相同的类型,所以通常您需要添加类似类型类约束的内容,而使用方法在这方面也有帮助。