![](/img/trans.png)
[英]Method parameter of dependent type of another implicit method parameter - is it possible?
[英]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工作,但我不喜歡傳遞任何周圍。 我希望編譯器能夠檢查傳入的內容。
您應該為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]) = {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.