微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何获得匹配类型以在Scala 3中正常工作

如何解决如何获得匹配类型以在Scala 3中正常工作

我很好奇我是否可以移植我的未键入项目以使用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的“类型过滤器”,因为它认为在这种情况下s的类型为"tag" | "attrs" | "children",而模式匹配情况下应将其减少为“标签”。

如何实现我要求的行为?

解决方法

正确是

List

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

请参阅第4项

  1. 匹配表达式模式没有后卫
  2. match表达式scrutinee的类型是match类型scrutinee的类型的子类型
  3. 匹配表达式和匹配类型的案例数相同
  4. 匹配表达式模式都是类型化模式,并且这些类型与其匹配类型中对应的类型模式//recursive but not tail-recursive def fromList(list1: List[Int]): Int = if (list1.isEmpty) 0 else 10 * fromList(list1.tail) + list1.head 相对应

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。