[英]How to get match type to work correctly in Scala 3
I was very curious to see if I could port my untyped project to be typed with Scala 3. Here was my start:我很好奇是否可以将我的无类型项目移植到 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
}
}
}
It does not compile, it throws an error:它不编译,它抛出一个错误:
> [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] | ]
I think it comes from the fact that it does not perceive the pattern matching as a "type filter" for s, since it believes that, in this case, s has the type "tag" | "attrs" | "children"
我认为这是因为它没有将模式匹配视为 s 的“类型过滤器”,因为它认为,在这种情况下,s 具有"tag" | "attrs" | "children"
类型"tag" | "attrs" | "children"
"tag" | "attrs" | "children"
"tag" | "attrs" | "children"
, whereas the pattern matching case should reduce it to "tag". "tag" | "attrs" | "children"
,而模式匹配的情况应该将其减少为 "tag" 。
How can I implement my requested behavior?如何实现我请求的行为?
Correct is正确的是
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 https://scastie.scala-lang.org/DmytroMitin/sHIgdt5wR7mKZyJm6vEXJA/1
See item 4 in见第 4 项
- The match expression patterns do not have guards匹配表达式模式没有保护
- The match expression scrutinee's type is a subtype of the match type scrutinee's type匹配表达式被审查者的类型是被审查者类型的匹配类型的子类型
- The match expression and the match type have the same number of cases匹配表达式和匹配类型的大小写相同
- The match expression patterns are all Typed Patterns , and these types are
=:=
to their corresponding type patterns in the match type匹配表达式模式都是 Typed Patterns ,这些类型是=:=
到它们在匹配类型中对应的类型模式
http://dotty.epfl.ch/docs/reference/new-types/match-types.html http://dotty.epfl.ch/docs/reference/new-types/match-types.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.