我正在从对象Node
创建一个实例。我的问题是如何在我的类中有一个函数为我返回对象名称。例如,像这样:
class Node (val in: Int) {
def getName() = ...
}
然后:
val testNode1 = new Node(5)
val testNode2 = new Node(4)
testNode1.getName() //Print: "testNode1"
testNode2.getName() //Print: "testNode2"
答案 0 :(得分:0)
我不知道如何使它与构造函数一起使用,但使用辅助def
宏可以工作:
---- build.sbt ----
scalaVersion := "2.12.4"
libraryDependencies +=
"org.scala-lang" % "scala-reflect" % scalaVersion.value % "provided"
----模块1(例如主要来源)----
---- Node.scala ----
package foo
class Node (val in: Int, val name: String)
---- Macros.scala ----
package foo
import scala.reflect.macros.blackbox
object Macros {
def newNode(c: blackbox.Context)(in: c.Expr[Int]): c.Expr[Node] = {
import c.universe._
val owner = c.internal.enclosingOwner
val name = if (owner.isTerm && owner.asTerm.isVal) {
owner.name.toString
} else {
"unknown"
}
val nameExpr = c.Expr(Literal(Constant(name)))
reify[Node] {
new Node(in.splice, nameExpr.splice)
}
}
}
----模块2(例如测试源)----
---- Test.scala ----
package foo
import scala.language.experimental.macros
object Test {
def Node(in: Int): Node = macro Macros.newNode
def main(args: Array[String]): Unit = {
val bar = Node(1234)
println(s"The node's name is ${bar.name}")
}
}