【问题标题】:How to use context bound to a class如何使用绑定到类的上下文
【发布时间】:2017-06-18 12:42:41
【问题描述】:

我在案例类中有一个值和上下文绑定到它的类型。在一个函数中,我想在绑定上下文中使用这个案例类及其包含的值。

例子:

object Example {
  trait ObjectLike[A] {
    def properties(a: A): Map[String, Any]
  }

  case class Person(name: String, age: Int)

  object Person {
    implicit val personObjectLike = new ObjectLike[Person] {
      override def properties(a: Person): Map[String, Any] = Map(
        "name" -> a.name,
        "age" -> a.age
      )
    }
  }

  case class Company(name: String, founded: Int)
  object Company {
    implicit val companyObjectLike = new ObjectLike[Company] {
      override def properties(a: Company): Map[String, Any] = Map(
        "name" -> a.name,
        "founded" -> a.founded
      )
    }
  }

  // I have the case class with the context bound here.
  case class ObjectStore[Obj : ObjectLike](objs: List[Obj])

  // Here is the function where I want to use it
  def getNames[A](store: ObjectStore[A]): List[String] = {
    store.objs
      .map((a) => {
        implicitly[ObjectLike[A]].properties(a).get("name").map(_.toString)
      })
      .flatten
  }
} 

然而,这不会编译。错误信息是

Error:(32, 19) could not find implicit value for parameter e: Example.ObjectLike[A]
        implicitly[ObjectLike[A]].properties(a).get("name").map(_.toString)

Error:(32, 19) not enough arguments for method implicitly: (implicit e: Example.ObjectLike[A])Example.ObjectLike[A].
Unspecified value parameter e.
        implicitly[ObjectLike[A]].properties(a).get("name").map(_.toString)

请注意,我不想用隐含的证据改变 getNames 的签名,我想以某种方式从课堂上召唤它,因为我认为它应该已经存在了。

【问题讨论】:

  • 如何在不为它添加隐含证据的情况下从课堂上召唤它?你不知道类是什么,它是一个泛型类型参数。

标签: scala


【解决方案1】:

您可以通过ObjectStore中的方法暴露证据。

case class ObjectStore[Obj : ObjectLike](objs: List[Obj]) {
  def evidence = implicitly[ObjectLike[Obj]]
}

那么你可以使用store.evidence来访问它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    相关资源
    最近更新 更多