如何在Scala中使用通配符来获得更高级的类型?

0__*_*0__ 7 scala wildcard higher-kinded-types

比方说我有这个特点

trait Ctx[C, V[_]]
Run Code Online (Sandbox Code Playgroud)

我无法构造任何采用Ctx的方法签名,其中第二个类型参数未指定(通配符).例如:

def test(c: Ctx[_, _]) = ()
Run Code Online (Sandbox Code Playgroud)

不编译("error: _$2 takes no type parameters, expected: one").我也不能这样做

def test(c: Ctx[_, _[_]]) = ()
Run Code Online (Sandbox Code Playgroud)

("error: _$2 does not take type parameters").我错过了什么?

huy*_*hjl 5

我能够定义这个:

def test[V[X]](c:Ctx[_,V]) {}
Run Code Online (Sandbox Code Playgroud)

它似乎适用于类型推断:

scala> trait Ctx[ C, V[ _ ]]
defined trait Ctx

scala> def test[V[X]](c:Ctx[_,V]) {}
test: [V[X]](c: Ctx[_, V])Unit

scala> class P extends Ctx[Int, List]
defined class P

scala> new P
res0: P = P@1f49969

scala> test(res0)
Run Code Online (Sandbox Code Playgroud)

编辑:我怀疑替换Ctx使用抽象类型是不切实际的,但这是我能够做到的:

trait Ctx[C] { type V[X] }
class CtxOption[C] extends Ctx[C] { type V[X] = Option[X] }
class CtxList[C] extends Ctx[C] { type V[X] = List[X] }

def test(ctx:Ctx[_]) { println(ctx) }

val ctxOptInt = new CtxOption[Int]
val ctxListStr = new CtxList[String]

test(ctxOptInt)
test(ctxListStr)

val list = collection.mutable.ListBuffer[Ctx[_]]()
list += ctxOptInt
list += ctxListStr
list
Run Code Online (Sandbox Code Playgroud)

使用V的抽象类型可以避免为通配符类型构造函数确定类型参数语法的复杂(或不可能)任务.另外,如ListBuffer示例中所示,您可以处理其中V不同类型构造函数的对象(在我的示例中为OptionList).我提供的第一个解决方案不允许你这样做.

编辑2:怎么样?

trait AbstractCtx[C] { type W[X] }
trait Ctx[C,V[_]] extends AbstractCtx[C] { type W[X] = V[X] }
def test(ctx:AbstractCtx[_]) { println(ctx) }
Run Code Online (Sandbox Code Playgroud)