Because of the type erasure of the JVM the above two methods are indistinguishable by the JVM at runtime. The general way to deal with type erasure issues is TypeTag
. You may use classTag
as well but classTag
is limited.
So, Instead of declaring two methods, declare one method with type parameter T
and at runtime figure out what T
is and proceed.
import scala.reflect.runtime.universe._
def insertBatch[T: TypeTag](sql: String, params: Seq[T]): Unit = typeOf[T] match {
case a if a =:= typeOf[Seq[String]] =>
val l = params.asInstanceOf[Seq[Seq[String]]]
// do something here
case b if b =:= typeOf[Map[String, String]] =>
val l = params.asInstanceOf[Seq[Map[String, String]]]
// do something here
case _ => //some other types
}
Scala REPL
scala> :paste
// Entering paste mode (ctrl-D to finish)
import scala.reflect.runtime.universe._
def insertBatch[T: TypeTag](sql: String, params: Seq[T]): Unit = typeOf[T] match {
case a if a =:= typeOf[Seq[String]] =>
val l = params.asInstanceOf[Seq[Seq[String]]]
println("bar")
case b if b =:= typeOf[Map[String, String]] =>
val l = params.asInstanceOf[Seq[Map[String, String]]]
println("foo")
case _ => println("ignore")
}
// Exiting paste mode, now interpreting.
import scala.reflect.runtime.universe._
insertBatch: [T](sql: String, params: Seq[T])(implicit evidence$1: reflect.runtime.universe.TypeTag[T])Unit
scala> insertBatch[Seq[String]]("", Seq(Seq("")))
bar
scala> insertBatch[Map[String, String]]("", Seq(Map.empty[String, String]))
foo
scala> insertBatch[String]("", Seq(""))
ignore