【问题标题】:How to get match type to work correctly in Scala 3如何让匹配类型在 Scala 3 中正常工作
【发布时间】:2021-02-02 15:11:40
【问题描述】:

我很好奇是否可以将我的无类型项目移植到使用 Scala 3 进行类型化。 这是我的开始:

object Main {
  type HtmlNodeRecord[X]= X match {
    case "tag" => String
    case "attrs" => List[(String, String)]
    case "children" => List[HtmlNode]
  }
  case class HtmlNode(tag: String, attrs: List[(String, String)], children: List[HtmlNode]) {
    def apply(s: "tag" | "attrs" | "children"):  HtmlNodeRecord[s.type] = s match {
      case "tag" => tag
      case "attrs" => attrs
      case "children" => children
    }
  }
}

不编译,报错:

> [E007] Type Mismatch Error: Main.scala:10:22
> [error] 10 |      case "tag" => tag
> [error]    |                    ^^^
> [error]    |   Found:    (HtmlNode.this.tag : String)
> [error]    |   Required: Main.HtmlNodeRecord[
> [error]    |     (s : ("tag" : String) | ("attrs" : String) | ("children" : String))
> [error]    |   ]

我认为这是因为它没有将模式匹配视为 s 的“类型过滤器”,因为它认为在这种情况下,s 的类型为 "tag" | "attrs" | "children",而模式匹配的情况应该将其简化为“标签”。

如何实现我请求的行为?

【问题讨论】:

    标签: scala scala-3 singleton-type dotty match-types


    【解决方案1】:

    正确的是

    type HtmlNodeRecord[X] = X match {
      case "tag" => String
      case "attrs" => List[(String, String)]
      case "children" => List[HtmlNode]
    }
    case class HtmlNode(tag: String, attrs: List[(String, String)], children: List[HtmlNode]) {
      def apply(s: "tag" | "attrs" | "children"): HtmlNodeRecord[s.type] = s match {
        case _: "tag" => tag
        case _: "attrs" => attrs
        case _: "children" => children
      }
    }
    

    https://scastie.scala-lang.org/DmytroMitin/sHIgdt5wR7mKZyJm6vEXJA/1

    参见第 4 项

    1. 匹配表达式模式没有保护
    2. 匹配表达式 scrutinee's type 是 match type scrutinee's type 的子类型
    3. 匹配表达式和匹配类型的 case 数相同
    4. 匹配表达式模式都是类型化模式,这些类型在匹配类型中对应的类型模式是=:=

    http://dotty.epfl.ch/docs/reference/new-types/match-types.html

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 2021-10-04
      • 2013-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      • 2015-05-19
      相关资源
      最近更新 更多