如何注入准引号数组

How to inject quasi quotes array

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

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 数组传递到准引号时,它在 class 构造函数前面使用了两个 ..,如下所示:

    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!

          }
        }"""