[英]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]
}
You can see my intent here. 你可以在这里看到我的意图。 I define a type in JsonOps to encapsulate a structure dependant on J. Then later when I want to use this, I have a function that implicitly passes a JsonOps[J] object and also a parameter of type ObjectFields. 我在JsonOps中定义了一个类型来封装依赖于J的结构。然后当我想使用它时,我有一个隐式传递JsonOps [J]对象的函数以及ObjectFields类型的参数。
Problem is, ObjectFields is defined in ops, which occurs after the stuff in the signature. 问题是,ObjectFields是在ops中定义的,它发生在签名中的东西之后。
How can I unscramble this? 我怎么解读这个?
The second def works, but I don't like passing Any around. 第二个def工作,但我不喜欢传递任何周围。 I'd like the compiler to be able to check what's being passed in. 我希望编译器能够检查传入的内容。
You should introduce one more type parameter for compilerLikey
and write JsonOps
with refinement 您应该为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 }) = {}
or using Aux-pattern 或使用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]) = {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.