[英]How to use context bound to a class
我在案例類中具有綁定到其類型的值和上下文。 在一個函數中,我想在綁定上下文中使用此case類及其包含的值。
例:
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
的簽名,我想以某種方式從類中召喚它,因為我認為它應該已經存在了。
您可以通過ObjectStore
的方法公開證據。
case class ObjectStore[Obj : ObjectLike](objs: List[Obj]) {
def evidence = implicitly[ObjectLike[Obj]]
}
然后,您可以使用store.evidence
進行訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.