How can I easily get a Scala case class's name?

前端 未结 6 1420
刺人心
刺人心 2021-01-31 13:32

Given:

case class FirstCC {
  def name: String = ... // something that will give \"FirstCC\"
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two =          


        
6条回答
  •  被撕碎了的回忆
    2021-01-31 14:26

    Here is a Scala function that generates a human-readable string from any type, recursing on type parameters:

    https://gist.github.com/erikerlandson/78d8c33419055b98d701

    import scala.reflect.runtime.universe._
    
    object TypeString {
    
      // return a human-readable type string for type argument 'T'
      // typeString[Int] returns "Int"
      def typeString[T :TypeTag]: String = {
        def work(t: Type): String = {
          t match { case TypeRef(pre, sym, args) =>
            val ss = sym.toString.stripPrefix("trait ").stripPrefix("class ").stripPrefix("type ")
            val as = args.map(work)
            if (ss.startsWith("Function")) {
              val arity = args.length - 1
              "(" + (as.take(arity).mkString(",")) + ")" + "=>" + as.drop(arity).head
            } else {
              if (args.length <= 0) ss else (ss + "[" + as.mkString(",") + "]")
            }
          }
        }
        work(typeOf[T])
      }
    
      // get the type string of an argument:
      // typeString(2) returns "Int"
      def typeString[T :TypeTag](x: T): String = typeString[T]
    }
    

提交回复
热议问题