簡體   English   中英

如何對所有具有上下文綁定的類進行模式匹配

[英]How to pattern match all classes with context bound

我有一個類型 class 和一些實例:

trait TC[T] { def doThings(x: T): Unit }
implicit val tcA = new TC[A] { /* ... */}
implicit val tcB = new TC[B] { /* ... */}
implicit val tcC = new TC[C] { /* ... */}
/* ... */

在我的呼叫站點中,我輸入為 Any,我需要檢查輸入實際類型是否存在隱式:

def process(in: Any) = in match {
  case x: A => implicitly[TC[A]].doThings(x)
  case x: B => implicitly[TC[B]].doThings(x)
  case x: C => implicitly[TC[C]].doThings(x)
  //...
}

這似乎乏味且不必要,因為我必須列出所有具有此類型 class 實例的類。 我可以通過以下方式實現這一目標:

def process(in: Any) = in match {
  case x: T : TC => implicitly[TC[T]].doThings(x) //This does not work
}

編輯:輸入是 Any(來自 Java 庫的 Object)。 不能在輸入上使用泛型或上下文綁定。

您需要要求一個隱含的TCAny將不起作用。 如下:

trait TC[T] { def doThings(x: T): Unit }

implicit def tcS: TC[String] = new TC[String] {
  override def doThings(x: String): Unit = println("string")
}

implicit def tcI: TC[Int] = new TC[Int] {
  override def doThings(x: Int): Unit = println("int")
}

def process[T : TC](x: T): Unit = implicitly[TC[T]].doThings(x)

process("")
process(1)
// process(4L) wont compile

試試看!

如果你真的想做你在問題中提到的事情,你可以寫如下,但如果你只想通過找到適當 TC 的隱式實例來調用 doThings - 請參閱 João Guitana 答案

object Main extends App {
  class A
  class B
  class C

  trait TC[T] { def doThings(x: T): Unit }
  implicit val tcA = new TC[A] {
    override def doThings(x: A): Unit = println("From A")
  }
  implicit val tcB = new TC[B] {
    override def doThings(x: B): Unit = println("From B")
  }
  implicit val tcC = new TC[C] {
    override def doThings(x: C): Unit = println("From C")
  }

  def process[T: ClassTag](in: T) = in match {
    case x: A => implicitly[TC[A]].doThings(x)
    case x: B => implicitly[TC[B]].doThings(x)
    case x: C => implicitly[TC[C]].doThings(x)
  }

  process(new A())
  process(new B())
  process(new C())

}
/* === Output ====
From A
From B
From C
*/

暫無
暫無

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

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