简体   繁体   English

条件 scalacOptions 与 SBT

[英]Conditional scalacOptions with SBT

I am using a project with cross-build for Scala 2.8, 2.9 and (hopefully) 2.10, using SBT. I would like to add the -feature option when compiling with 2.10 only.我正在使用 Scala 2.8、2.9 和(希望)2.10 的交叉构建项目,使用 SBT。我想在仅使用 2.10 编译时添加-feature选项。

In other words, when I compile with a version smaller than 2.10.0, I would like to set the compiler options as:换句话说,当我用小于 2.10.0 的版本编译时,我想将编译器选项设置为:

scalacOptions ++= Seq( "-deprecation", "-unchecked" )

and when compiling with a version greater or equal than 2.10.0:当使用大于或等于 2.10.0 的版本进行编译时:

scalacOptions ++= Seq( "-deprecation", "-unchecked", "-feature" )

Is there a way to achieve this?有没有办法做到这一点?

When cross-building, scalaVersion reflects the version your project is currently built against. 在交叉构建时,scalaVersion会反映您的项目当前构建的版本。 So depending on scalaVersion should do the trick: 所以取决于scalaVersion应该做的伎俩:

val scalaVersionRegex = "(\\d+)\\.(\\d+).*".r
...
scalacOptions <++= scalaVersion { sv =>
  sv match {
    case scalaVersionRegex(major, minor) if major.toInt > 2 || (major == "2" && minor.toInt >= 10) =>
      Seq( "-deprecation", "-unchecked", "-feature" )
    case _ => Seq( "-deprecation", "-unchecked" )
}

I found this was quick and concise way of doing it: 我发现这是一种快速而简洁的方法:

scalaVersion := "2.10.0"

crossScalaVersions := "2.9.2" :: "2.10.0" :: Nil

scalacOptions <<= scalaVersion map { v: String =>
  val default = "-deprecation" :: "-unchecked" :: Nil
  if (v.startsWith("2.9.")) default else default :+ "-feature"            
}

There is CrossVersion.partialVersion now which can be used for this.现在有CrossVersion.partialVersion可以用于此。 I am not sure which SBT it was introduced in, but it seems to work fine even in 0.13.8:我不确定它是在哪个 SBT 中引入的,但即使在 0.13.8 中它似乎也能正常工作:

    scalacOptions ++= {
      if (CrossVersion.partialVersion(scalaVersion.value).exists(_ >= (2, 10))) {
        Seq("-deprecation", "-unchecked", "-feature")
      } else {
        Seq("-deprecation", "-unchecked")
      }
    }

Note: you need to import scala.math.Ordering.Implicits._ to be able to use >= operator on tuples.注意:您需要import scala.math.Ordering.Implicits._才能在元组上使用>=运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM