用于递归泛型定义的 Scala 通配符

Scala wildcard for recursive generic definition

假设有如下特征定义:

trait MyTrait[A, B <: MyTrait[A, B]] 有一个实现:

class MyClass extends MyTrait[Int, MyClass]

如何编写通用部分函数的签名来过滤 MyTrait 的任何实例?

def filterMyTrait: PartialFunction[MyTrait[_, _], Boolean] = {
  case myClass: MyClass => true
}

def filterMyTrait: PartialFunction[MyTrait[_, _ <: MyTrait[_, _]], Boolean]  = {
  case myClass: MyClass => true
}

两者都在编译时失败

type arguments [_,_] do not conform to trait MyTrait's type parameter bounds [A,B <: MyTrait[A,B]] def filterMyTrait: PartialFunction[MyTrait[_, _ <: MyTrait[_, _]], Boolean] = {

尝试使您的方法通用

def filterMyTrait[A, B <: MyTrait[A, B]]: PartialFunction[MyTrait[A, B], Boolean] = {
  case myClass: MyClass => true
}

或使用存在类型

def filterMyTrait: PartialFunction[MyTrait[A, B] forSome {type A; type B <: MyTrait[A, B]}, Boolean] = {
  case myClass: MyClass => true
}