Nice programing

Scala 케이스 클래스의 이름을 어떻게 쉽게 얻을 수 있습니까?

nicepro 2020. 12. 28. 22:32
반응형

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?


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

NB 케이스 클래스를 확장하는 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]
}

참조 URL : https://stackoverflow.com/questions/2656364/how-can-i-easily-get-a-scala-case-classs-name

반응형