gysyky
gysyky

Reputation: 470

Matching ClassTag with another field in a case class

Is there a way I can make following piece of code work? Expected result is that one of the promises in the list will be completed (the one with matching String type).

import scala.concurrent.Promise
import scala.reflect.ClassTag

case class Test[T](promise: Promise[T], tag: ClassTag[T])

def createTest[T](implicit tag: ClassTag[T]) = Test(Promise[T](), tag)

val seq: Seq[Test[_]] = Seq(createTest[String], createTest[Int])

seq.foreach { case Test(promise, tag) =>
  "asd" match {
    case tag(s) => promise.success(s)
    case _ => // nothing
  }
}

currently it yields the error:

found : s.type (with underlying type Any)

required: _$1 where type _$1

Upvotes: 0

Views: 220

Answers (1)

gysyky
gysyky

Reputation: 470

I found a solution using Class instead of ClassTag:

import scala.concurrent.Promise

case class Test[T](promise: Promise[T], clazz: Class[T])

def createTest[T](clazz: Class[T]) = Test(Promise[T](), clazz)

val seq: Seq[Test[_]] = Seq(createTest[String](classOf[String]), createTest[Int](classOf[Int]))

seq.foreach { case Test(promise, clazz) =>
  val obj = "asd"
  if (clazz.isInstance(obj)) promise.success(clazz.cast(obj))  
}

Upvotes: 1

Related Questions