如何拥有类型依赖于隐式参数的方法参数? [英] 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 类型的参数.
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.
问题是,ObjectFields 是在 ops 中定义的,它发生在签名中的东西之后.
Problem is, ObjectFields is defined in ops, which occurs after the stuff in the signature.
我该如何解读?
第二个 def 有效,但我不喜欢传递 Any .我希望编译器能够检查传入的内容.
The second def works, but I don't like passing Any around. I'd like the compiler to be able to check what's being passed in.
推荐答案
你应该为 compilerLikey
再引入一个类型参数,并细化编写 JsonOps
You should introduce one more type parameter for compilerLikey
and write JsonOps
with refinement
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 }) = {}
或使用辅助模式>
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]) = {}
这篇关于如何拥有类型依赖于隐式参数的方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!