gpt4 book ai didi

具有类型参数的类的 Scala 模式匹配

转载 作者:行者123 更新时间:2023-12-04 02:15:24 25 4
gpt4 key购买 nike

我正在尝试使用类型化参数对自定义类进行模式匹配:

class Foo[A]

def isMyFoo[A: ClassTag](v: Any) = v match {
case mine: Foo[A] => "my foo"
case other: Foo[_] => "not my foo"
case _ => "not a foo"
}

那是行不通的;无论 Foo 的类型如何,我总是会得到 "my foo"

我能够做出这样的作品的唯一方法是:

class Foo[A](implicit t: ClassTag[A]) {
val tag = t
}

def isMyFoo[A: ClassTag](v: Any) = v match {
case foo: Foo[_] =>
if (foo.tag == classTag[A]) "my foo"
else "not my foo"
case _ => "not a foo"
}

有没有更优雅的方式呢?我是否必须将 ClassTag 保留在 Foo 中?

最佳答案

Do I have to keep the ClassTag inside Foo?

是的。 Foo 的类型参数在运行时被删除,所以你所知道的就是你有一个 Foo[_]。解决此问题的唯一方法是使用 ClassTagTypeTag 保存类型信息。如果您要走这条路,我建议您使用 TypeTag,因为您将能够使用更精确的类型。 ClassTag 仍然只能进行模类型删除。

例如,使用ClassTag,这是错误的:

scala> val fooListString = new Foo[List[String]]
fooListString: Foo[List[String]] = Foo@f202d6d

scala> isMyFoo[List[Int]](fooListString)
res4: String = my foo

但以下将起作用:

class Foo[A](implicit t: TypeTag[A]) {
val tag = t
}

def isMyFoo[A: TypeTag](v: Any) = v match {
case foo: Foo[_] =>
if (foo.tag.tpe =:= typeOf[A]) "my foo"
else "not my foo"
case _ => "not a foo"
}

scala> val fooListString = new Foo[List[String]]
fooListString: Foo[List[String]] = Foo@6af310c7

scala> isMyFoo[List[Int]](fooListString)
res5: String = not my foo

关于具有类型参数的类的 Scala 模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34499114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com