Как я могу легко получить имя класса Scala Case?
Вопрос
Дано:
case class FirstCC {
def name: String = ... // something that will give "FirstCC"
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two = SecondCC()
Как я могу получить "FirstCC"
от one.name
и "SecondCC"
от two.name
?
Решение
def name = this.getClass.getName
Или если вы хотите только имя без пакета:
def name = this.getClass.getSimpleName
Увидеть документацию java.lang.class.lass. за дополнительной информацией.
Другие советы
Вы можете использовать свойство productPrefix
класса дела:
case class FirstCC {
def name = productPrefix
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two = SecondCC()
one.name
two.name
NB Если вы пройдете к SCALA 2.8, расширяя класс Case, были устарены, и вы не должны забывать левый и правый родитель ()
class Example {
private def className[A](a: A)(implicit m: Manifest[A]) = m.toString
override def toString = className(this)
}
def name = this.getClass.getName
Вот функция Scala, которая генерирует читаемую людскую строку из любого типа, рекурсируя параметры типа:
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]
}
Не связан с StackOverflow