gpt4 book ai didi

scala - 如何注入(inject)准引号数组

转载 作者:行者123 更新时间:2023-12-01 17:55:10 27 4
gpt4 key购买 nike

我有一个名为 definitions 的准引用数组,我想将其注入(inject)准引用。我该怎么做?

private def generateDaoComponent(files: Array[File]) = {
val file = createNewFile(compDirectory)

val definitions = files.map(f => {
val daoName = f.getName.replace(".java", "")
val daoType = TypeName(daoName)
val daoTerm = TermName(daoName)

q"""def $daoTerm = getValueOrInstantiate($daoName, () => new $daoType(configuration))


"""
})

val tree = q"""
package database.dao {
import org.jooq.SQLDialect
import org.jooq.impl.DefaultConfiguration
import utility.StrongHashMap

trait $componentType extends StrongHashMap[String, Dao] {
this: DaoManager =>

private lazy val configuration = new DefaultConfiguration().set(connection).set(SQLDialect.POSTGRES_9_4)

${definitions.foreach(f => q"${f}")}
}
}"""

writeToFile(file, tree)
}

最佳答案

这是一些疯狂的深夜编码,但多亏了这个网站,我找到了它

3 approaches to Scala code generation

我注意到当它将 $params 数组传递到准引用时,它在类构造函数前面使用了两个 ..,如下所示:

    val params = schema.fields.map { field =>
val fieldName = newTermName(field.name)
val fieldType = newTypeName(field.valueType.fullName)
q"val $fieldName: $fieldType"
}

val json = TypeSchema.toJson(schema)

// rewrite the class definition
c.Expr(
q"""
case class $className(..$params) {

def schema = ${json}

}
"""
)

我在问题中发布的代码有两个步骤可以使其正常工作。

1) 将$definitions.toList 转换为列表

2)在前面加上两个..

最后的代码是这样的:

    val definitions = files.map(f => {
val daoName = f.getName.replace(".java", "")
val daoType = TypeName(daoName)
val daoTerm = TermName(new StringBuilder("get").append(daoName).toString())

q"""def $daoTerm = getValueOrInstantiate($daoName, () => new $daoType(configuration))"""
}).toList <--- HERE!

val tree = q"""
package database.dao {
import org.jooq.SQLDialect
import org.jooq.impl.DefaultConfiguration
import utility.StrongHashMap

trait $componentType extends StrongHashMap[String, Dao] {
this: DaoManager =>

private lazy val configuration = new DefaultConfiguration().set(connection).set(SQLDialect.POSTGRES_9_4)

..$definitions <-- AND HERE!

}
}"""

关于scala - 如何注入(inject)准引号数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32123943/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com