如何在Scala中合并多个导入? [英] How to merge multiple imports in scala?
本文介绍了如何在Scala中合并多个导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个图书馆a.com.每次在每个文件中,我都需要导入很多程序包,例如
Assume I have a library a.com. Everytime and in each file, I need to import a lot of package like
import a.com._
import a.com.b._
import a.com.c
import a.com.Implicits._
我不想每次都在的每个文件中编写这些代码 另一个项目.
I don't want to write these code every time in each file of another project.
此外,如果我想将a.com
更改为a.net
,则必须更改每个文件.
Also if I want to change a.com
to a.net
, I have to change every file.
反正有防止这种情况发生吗?
Is there anyway to prevent this?
推荐答案
您可以生成源
build.sbt
lazy val commonSettings = Seq(
scalaVersion := "2.13.1",
)
lazy val in = project
.settings(
commonSettings,
)
lazy val out = project
.settings(
sourceGenerators in Compile += Def.task {
Generator.gen(
inputDir = sourceDirectory.in(in, Compile).value,
outputDir = sourceManaged.in(Compile).value
)
}.taskValue,
commonSettings,
)
project/build.sbt
libraryDependencies += "org.scalameta" %% "scalameta" % "4.2.3"
project/Generator.scala
import sbt._
object Generator {
def gen(inputDir: File, outputDir: File): Seq[File] = {
val finder: PathFinder = inputDir ** "*.scala"
for(inputFile <- finder.get) yield {
val inputStr = IO.read(inputFile)
val outputFile = outputDir / inputFile.toURI.toString.stripPrefix(inputDir.toURI.toString)
val outputStr = Transformer.transform(inputStr)
IO.write(outputFile, outputStr)
outputFile
}
}
}
project/Transformer.scala
import scala.meta._
object Transformer {
def transform(input: String): String = transform(input.parse[Source].get).toString
def transform(input: Tree): Tree = input match {
case source"..${List(q"package $eref { ..$stats }")}" =>
q"""package $eref {
import a.com._
import a.com.b._
import a.com.c
import a.com.Implicits._
..$stats
}"""
}
}
in/src/main/scala/com/example/App.scala
package com.example
object App {
}
out/target/scala-2.13/src_managed/main/scala/com/example/App.scala (在sbt "; project out; clean; compile"
之后)
package com.example
import a.com._
import a.com.b._
import a.com.c
import a.com.Implicits._
object App
这篇关于如何在Scala中合并多个导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文