How to find class parameter datatype at runtime in scala

后端 未结 2 567
谎友^
谎友^ 2021-01-27 23:40
import scala.reflect.runtime.universe
import scala.reflect.runtime.universe._

def getType[T: TypeTag](obj: T) = typeOf[T]

case class Thing(
  val id: Int,
  var name:          


        
2条回答
  •  执笔经年
    2021-01-28 00:10

    @Dmytrio answer is a great explanation why the reflection didn't work as you expected.

    I can understand from your question, that what you are trying to do, is actually pattern match all variables you have in a case class. Please consider doing it in the following way:

    case class Thing(id: Int, name: String)
    val thing = Thing(1, "Apple")
    
    thing.productIterator.foreach {
      case t: Int => println(s"I am Int: $t")
      case t: String => println(s"String, Do some stuff: $t")
      case t => println(s"Absurd: $t")
    } 
    

    Code run at Scastie.

提交回复
热议问题