How to use multiple versions of a library in Scala

2020-03-21 05:47发布

问题:

I am using a library say A in Scala which is dependent on version x.11 of another library say Z.

Now, I am also using a library say B which is dependent on version x.31 of Z.

This leads to compile error because we will have two versions of library Z, how can I use both libraries A and B in scala's sbt? Is there any way to specify it.

回答1:

If completely replacing one dependency with a newer version happens to work, then Sparko's solution works. However, that isn't always the case.

If you want to include both versions of a library in the uber-jar produced by sbt-assembly, you'll need to use shading. See this post for an overview of what shading is, and some of the drawbacks associated with it.

Shading is covered in sbt-assembly's documentation here, but if you're anything like me, their way of explaining it will leave you more confused than you started. There's a good blog post, Spark, Uber Jars and Shading with sbt-assembly, that helps to demystify it a bit. Here's the relevant section:

I can shade over my typesafe config version, giving it a different name so Spark won’t get confused between the versions. I quickly went to my build.sbt file, and added the following code:

assemblyShadeRules in assembly := Seq(
ShadeRule.rename("com.typesafe.config.**" -> "my_conf.@1") .inLibrary("com.typesafe" % "config" % "1.3.0") .inProject )

According to the documentation, this should place any class under com.typesafe.config under the new package my_conf.

For your case, the solution would be adding something like this to your build.sbt file:

assemblyShadeRules in assembly := Seq(
      ShadeRule.rename("com.somecompany.**" -> "my_conf.@1")
      .inLibrary("com.somecompany" % "libraryZ" % "0.11")
      .inProject
    )


回答2:

In sbt, conflicts between libraries are configured using the conflict manager. By default, the latest revision is selected but this can also be overridden in you .sbt file:

conflictManager := ConflictManager.strict

If you're using sbt 0.13.6 or greater you will be warned when you have an incompatible binary version between your dependencies. In this situation, you could configure an override in your sbt file for the specific library:

dependencyOverrides += "org.raman" % "Z" % "x.11"

This will force the resolved version of Z to x.11 but not pull a direct dependency in.



标签: scala sbt