1
我試圖爲接受case類值的函數生成Tree
,並返回給定位置的case類參數值。這對提取私有參數的值很有用。在插入字符串之前插入字符串(運行時quasiquote?)
import reflect.runtime.currentMirror
import scala.reflect.runtime.universe._
import scala.tools.reflect.ToolBox
val tb = currentMirror.mkToolBox()
case class A(private val first: Int)
case class B(first: Int, private val second: Int)
def get(tpe: Type, position: Option[Int]): Tree = {
val pos = s"${position.map(p => s"._${p + 1}").getOrElse("")}"
tb.parse(s"(a: $tpe) => $tpe.unapply(a).get$pos")
}
println(tb.eval(get(typeOf[A], None)).asInstanceOf[(A) => Int](A(1)))
println(tb.eval(get(typeOf[B], Some(1))).asInstanceOf[(B) => Int](B(1, 2)))
此外,我加入以下相關:
scalaVersion := "2.11.8"
libraryDependencies ++= Seq(
"org.scala-lang" % "scala-reflect" % scalaVersion.value,
"org.scala-lang" % "scala-compiler" % scalaVersion.value
)
position
是None
當殼體類只有一個參數。
我的解決方案的工作,但我怎麼能擺脫tb.parse(s"...")
和與quasiquoteq"..."
更換呢?
我試過,但它失敗:
Don't know how to unquote here
[error] q"(a: $tpe) => $tpe.unapply(a).get$pos"
[error] ^
當我明白我不能插入成在運行時被構建和q"..."
在編譯時解析不像tb.parse
quasiquote一些字符串。 對嗎?
也可以像那樣插入s"(a: $tpe) => $tpe.unapply(a).get$pos"
?當使用q"..."
語法時,quasiquote知道$tpe
是Type
,但字符串插值會從中產生字符串。我不確定這是否會始終工作,在更復雜和特殊的情況下。
我錯過了'Select'。有沒有關於這方面的詳細文檔? – mixel
http://scala-lang.org/api/current/scala-reflect。 'Select'是'x.y'中的'.'。 – HTNW