【问题标题】:Scala match on generic typeScala 匹配泛型类型
【发布时间】:2013-12-21 08:15:04
【问题描述】:

是否可以在返回类型 A 上以某种方式匹配,如果它是例如一个 int,做一个返回 int 的计算。 请参见以下示例:

def test[A](a: A):A = a match{
    case b: Int => b * 5
    case _ => a
}

错误信息:

type mismatch;  found   : Int  required: A

谢谢!

【问题讨论】:

    标签: scala generics pattern-matching


    【解决方案1】:

    你可以改回Any

    def test[A](a: A):Any = a match{
      case b: Int => b * 5
      case _ => a
    }
    

    另一种选择是做instanceof

    case b: Int => (b * 5).asInstanceOf[A]

    【讨论】:

    • 为什么 OP 的代码不能编译?也就是说,为什么 scala 无法判断在第一种情况下,AInt,所以可以返回Int?看来 scala 应该 能够分辨出来。我怀疑原因与运行时与编译时类型检查有关。
    【解决方案2】:

    是的:

    def test(a : Int) = a * 5
    def test[A](a : A) = a
    

    Scala 支持重载方法和基于类型的调度,因此在这种情况下,您不必求助于模式匹配。

    【讨论】:

    • test(3)test(3.asInstanceOf[Any]) 会导致使用不同的函数,即使在第二种情况下它也是 Int
    • 确实如此,但返回类型不是从参数类型静态确定的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 2013-07-06
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    相关资源
    最近更新 更多