일부 클래스 이름을 기반으로 매크로를 사용하여 잘 유형화 된 인스턴스를 만들 수 있기를 원합니다. 예를 들어 나는 그렇게 같은 Long
인스턴스를 만들 수 있도록하려면 :매크로를 사용하여 컴파일 할 때 잘 형식화 된 인스턴스 생성
def fromName[T](typeName: String) = macro FromNameMacro.impl[T]
// will typecheck ok
fromName("scala.Long") ==== 0L
// will not typecheck ok
fromName("scala.Long") ==== ""
구현 될 법한 :
import scala.reflect.macros.Context
object FromNameMacro {
def impl[T: c.WeakTypeTag](c : Context)(klassName: c.Expr[String]): c.Expr[T] = {
import c.{universe => u}; import u._
val name = klassName.tree match { case Literal(Constant(n)) => n.toString }
// of course this doesn't work...
reify(this.getClass.getClassLoader.loadClass(name).newInstance.asInstanceOf[T])
}
}
내 질문
은 다음과 같습니다내가 무엇을 할 매개 변수에 따라 유형이 달라 지므로 매크로가 올바른 유형의 객체를 반환하도록해야합니까?
Scala 2.10을 사용하는 것이 가능합니까? 매크로 반환 올바른 유형의 결과를 갖는
, 2.10.x에서 매우 간단합니다 매크로 천국에서만 가능합니다. http://docs.scala-lang.org/overviews/macros/inference.html – Eric
Miles의 답변과 함께 http://stackoverflow.com/questions/13669974/static-return을 참조하십시오. -type-of-scala-macros –