【问题标题】:How to get match type with multiple type parameters to work correctly in Scala 3如何获得具有多个类型参数的匹配类型以在 Scala 3 中正常工作
【发布时间】:2021-12-18 15:10:07
【问题描述】:

我试图了解 Match 类型中的多种类型。即使下面的作品

type C2[N, M] = (N,M) match {
    case (String, Int) => Int 
    case (String, String) => Int 
    case (Int, String) => Int 
}
 
def fn[M,N](x:N,y:M):C2[N,M] = (x,y) match {
    case xx: (String, Int) @unchecked => xx(0).size + xx(1)
    case xx: (String, String) @unchecked => xx(0).size + xx(1).size
    case xx: (Int, String) @unchecked => xx(0) + xx(1).size
}

但即使匹配类型工作正常,我也无法按照样式工作

scala> type C2[N, M] = N match {
     |     case String => M match {
     |             case Int => Int
     |             }
     | }

scala> def fn[M,N](x:N,y:M):C2[x.type,y.type] = x match {
     |     case xx:String => y match {
     |             case yy:Int => (xx.size + yy)
     |             }
     | }
-- Error:
3 |            case yy:Int => (xx.size + yy)
  |                            ^^^^^^^^^^^^
  |                            Found:    Int
  |                            Required: (y : M) match {
  |                              case Int => Int
  |                            }

scala>

【问题讨论】:

    标签: scala scala-3 match-types


    【解决方案1】:

    我得到它的工作如下

    type C1Str[M] = M match {
        case Int => Int
        case String => Int
    }
    
    type C1Int[M] = M match {
        case String => Int
    }
    
    type C2[N, M] = N match {
      case String => C1Str[M]
      case Int => C1Int[M]
    }
     
    def fn[M,N](x:N,y:M):C2[N,M] = x match {
      case x: String => y match {
        case y: Int => x.size + y
        case y: String => x.size + y.size
      }
      case x: Int => y match {
        case y: String => x + y.size
      }
    }
    

    如果你想创建一个包含多个类型参数的匹配类型,你需要为每个 case 设置另一个匹配类型。

    【讨论】:

      猜你喜欢
      • 2021-02-02
      • 2016-04-02
      • 2021-08-13
      • 2013-06-14
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      相关资源
      最近更新 更多