如何拥有类型依赖于隐式参数的方法参数? [英] How can I have a method parameter with type dependent on an implicit parameter?

查看:38
本文介绍了如何拥有类型依赖于隐式参数的方法参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆