Conditional scalacOptions with SBT
Asked Answered
T

3

8

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.

In other words, when I compile with a version smaller than 2.10.0, I would like to set the compiler options as:

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

and when compiling with a version greater or equal than 2.10.0:

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

Is there a way to achieve this ?

Twoway answered 27/9, 2012 at 16:43 Comment(1)
take a look at scalaz: github.com/scalaz/scalazDashed
E
6

When cross-building, scalaVersion reflects the version your project is currently built against. So depending on scalaVersion should do the trick:

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" )
}
Equalitarian answered 27/9, 2012 at 19:16 Comment(0)
C
8

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"            
}
Clayborne answered 5/1, 2013 at 0:0 Comment(0)
E
6

When cross-building, scalaVersion reflects the version your project is currently built against. So depending on scalaVersion should do the trick:

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" )
}
Equalitarian answered 27/9, 2012 at 19:16 Comment(0)
U
0

There is CrossVersion.partialVersion now which can be used for this. I am not sure which SBT it was introduced in, but it seems to work fine even in 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.

Unmake answered 22/4, 2022 at 16:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.