gpt4 book ai didi

scala - 提取程序:推断的类型参数X不符合方法未应用的类型参数范围

转载 作者:行者123 更新时间:2023-12-01 07:14:45 25 4
gpt4 key购买 nike

在以下示例中,Scala无法使用提取器,这使我发疯:

trait Sys[S <: Sys[S]]

object Element {
object Foo {
def unapply[S <: Sys[S]](foo: Foo[S]): Option[Any] = ???
}
trait Foo[S <: Sys[S]] extends Element[S]
}
trait Element[S <: Sys[S]]

这是一个测试用例:
def test[S <: Sys[S]](elem: Element[S]) = elem match {
case Element.Foo(_) => ???
case _ => ???
}

失败
inferred type arguments [S] do not conform to method unapply's type parameter
bounds [S <: Sys[S]]

(在Scala 2.9.2和2.10中均如此)。

如果我删除F边界,它将起作用:
trait Sys

object Element {
object Foo {
def unapply[S <: Sys](foo: Foo[S]): Option[Any] = ???
}
trait Foo[S <: Sys] extends Element[S]
}
trait Element[S <: Sys]

def test[S <: Sys](elem: Element[S]) = elem match {
case Element.Foo(_) => ???
case _ => ???
}

我猜这是那些“讨厌斯卡拉时代”之一。可以这么愚蠢吗?基本上,它与 this question相同,没有正确的答案。

谢谢。

最佳答案

尝试使用test参数和null类型参数调用Sys[Any]时,确实表示:

type arguments [Sys[Any]] do not conform to trait Element's type parameter 
bounds [S <: Sys[S]]

尝试方差:
trait Sys[-S]

object Element {
object Foo {
def unapply[S <: Sys[S]](foo: Foo[S]): Option[Any] = ???
}
trait Foo[S <: Sys[S]] extends Element[S]
}
trait Element[S <: Sys[S]]

def test[S <: Sys[S]](elem: Element[S]) = elem match {
case f: Element.Foo[S] => "ok"
case _ => "smth else"
}

// test
test(new Element.Foo[Sys[Any]](){}) // "smth else"
test(new Element[Sys[Any]](){}) // "ok"

关于scala - 提取程序:推断的类型参数X不符合方法未应用的类型参数范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14672468/

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