Подтвердить что ты не робот

Как я могу легко получить имя класса класса Scala?

Дано:

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?

4b9b3361

Ответ 1

def name = this.getClass.getName

Или, если вы хотите только имя без пакета:

def name = this.getClass.getSimpleName

Подробнее см. документацию java.lang.Class.

Ответ 2

Вы можете использовать свойство productPrefix класса case:

case class FirstCC {
  def name = productPrefix
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two = SecondCC()

one.name
two.name

N.B. Если вы переходите к scala 2.8, расширяющему класс case, устарели, и вы не должны забывать левого и правого родителей ()

Ответ 3

def name = this.getClass.getName

Ответ 4

class Example {
  private def className[A](a: A)(implicit m: Manifest[A]) = m.toString
  override def toString = className(this)
}

Ответ 5

Вот функция 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]
}