簡體   English   中英

如何在 Scala 中通過動態輸入來選擇 typeclass

[英]How to choose typeclass by dynamic input in Scala

有一個帶有列的光滑表:

def name: Rep[Option[String]] = ???
def email: Rep[String] = ???
def fraudScores: Rep[Int] = ???

還有 typeclass 來計算不同字段的速率:

trait Rater[T] {
  def apply(rep: T): Result
}

object Rater {
  def getRater[T](t: T)(implicit rater: Rater[T]): Result = rater(t)

  implicit val int: Rater[Rep[Int]] = v => calculateRate(v, _)
  implicit val str: Rater[Rep[String]] = v => calculateRate(v, _)
  implicit val strOpt: Rater[Rep[Option[String]]] = v => calculateRate(v, _)
}

和 map:

val map: Map[String, Rep[_ >: Option[String] with String with Int]] = Map(
  "name" -> name,
  "email" -> email,
  "scores" -> fraudScores
)

我想做的是根據動態輸入獲取正確的實例,例如:

val fname = "scores" // value getting from http request
map.get(fname).fold(default)(f => {
    val rater = getRater(f)
    rater(someVal)
})

但是收到錯誤,即Rep[_ >: Option[String] with String with Int]沒有隱式,是否有一些解決方法?

我認為,您的問題是Map是一種錯誤的表示方式。 使用案例 class:

    case class Foo(
       name: Rep[Option[String]], 
       email: Rep[String], 
       score: Rep[Int]
    )

    def applyRater[T : Rater](t: T) = implicitly[Rater[T]](t)
    def rate(foo: Foo, what: String) = what match {
      case "name" => applyRater(foo.name)
      case "email" => applyRater(foo.email)
      case "score" => applyRater(foo.score)
      case _ => default
    }
    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM