与えられた:
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のドキュメントを参照してください。
productPrefix
ケースクラスのプロパティを使用できます。
case class FirstCC {
def name = productPrefix
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two = SecondCC()
one.name
two.name
注意:scala 2.8にパスした場合、ケースクラスの拡張は非推奨になり、左右の親を忘れないようにする必要があります()
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]
}
def name = getClass.getSimpleName.split('$').head
$1
これにより、一部のクラスの最後に表示されるものが削除されます。