我怎样才能拥有一个类型依赖于隐式参数的方法参数?

How can I have a method parameter with type dependent on an implicit parameter?

trait JsonOps[J] {
  type ObjectFields
  def partitionObjectFields(fields: ObjectFields, fieldNames: List[String]): (ObjectFields, ObjectFields)
}

def compilerNoLikey[J](stuff: ops.ObjectFields)(implicit ops:JsonOps[J]) = {}

def compilerLikey[J](stuff: Any)(implicit ops:JsonOps[J]) = {
    val stuff2 = stuff.asInstanceOf[ops.ObjectFields]
}

你可以在这里看到我的意图。我在JsonOps中定义了一个类型来封装一个依赖于J的结构。然后当我想使用它时,我有一个隐式传递一个JsonOps[J]对象的函数,还有一个ObjectFields类型的参数。

问题是,ObjectFields 是在 ops 中定义的,它发生在签名中的内容之后。

我该如何解读这个?

第二个 def 有效,但我不喜欢传递 Any。我希望编译器能够检查传入的内容。

你应该为compilerLikey多引入一个类型参数并写成JsonOps细化

trait JsonOps[J] {
  type ObjectFields
  def partitionObjectFields(fields: ObjectFields, fieldNames: List[String]): (ObjectFields, ObjectFields)
}

def compilerLikey[J, OF](stuff: OF)(implicit ops: JsonOps[J] { type ObjectFields = OF }) = {}

或使用Aux-pattern

trait JsonOps[J] {
  type ObjectFields
  def partitionObjectFields(fields: ObjectFields, fieldNames: List[String]): (ObjectFields, ObjectFields)
}

object JsonOps {
  type Aux[J, OF] = JsonOps[J] { type ObjectFields = OF }
}

def compilerLikey[J, OF](stuff: OF)(implicit ops: JsonOps.Aux[J, OF]) = {}