具有文字类型的 Scala 3 "a match type could not be fully reduced"

Scala 3 "a match type could not be fully reduced" with literal types

我正在学习 Scala 3,我对匹配类型和文字类型很感兴趣。

我想编写一个函数,该函数采用几种文字类型之一,并且 return 将特定类型作为传入文字类型的函数。

这是我正在尝试做的一个相当简单的例子:

type TestMatchType[T] = T match
  case "String1" => Int
  case "String2" => String

def testMatchType[T](input: T): TestMatchType[T] =
  input match
    case "String1": "String1" => 1
    case "String2": "String2" => "Two"

val string1Output: Int = testMatchType("String1")

换言之:

但是,当我尝试编译上面的代码时,出现以下错误:

1 |val string1Output: Int = testMatchType("String1")
  |                         ^^^^^^^^^^^^^^^^^^^^^^^^
  |               Found:    TestMatchType[String]
  |               Required: Int
  |
  |               Note: a match type could not be fully reduced:
  |
  |                 trying to reduce  TestMatchType[String]
  |                 failed since selector  String
  |                 does not match  case ("String1" : String) => Int
  |                 and cannot be shown to be disjoint from it either.
  |                 Therefore, reduction cannot advance to the remaining case
  |
  |                   case ("String2" : String) => String

我正在尝试理解该错误消息。我很难理解“selector String does not match case ("String1" : String) => Int”这一行。如果有办法使这项工作成功,我希望得到一些建议。

谢谢!

您不需要使用"foo": "foo",只需使用_: "foo"

但是,错误发生是因为T不会被推断为单例类型,所以return类型永远不会是IntString,它将保持 TestMatchType[String]。您必须使用 T <: Singleton 或使用 input.type 作为 TestMatchType 的参数(我更喜欢后者)。

def testMatchType[T](input: T): TestMatchType[input.type] =
  input match
    case _: "String1" => 1
    case _: "String2" => "Two"

Scastie