When are two classes with same definition and classpath chosen ambiguously in Scala with SBT and Ivy?

Viewed 146

In Scala, using sbt, I'm curious what I can expect if I:

  1. Define two different classes with same name, definition, and classpath in two differently named libraries (imagine case class User(name: String, age: Int) in two places, but one has require(age >= 0))
  2. Depend on those two libraries in build.sbt
  3. Reference that class in code that successfully compiles and passes tests
  4. Publish that code as a library that is then run elsewhere

My specific question is, At what points are those classes chosen ambiguously? That is, at what points of the compilation, publishing, and application launch processes might the prevailing class alternate between one definition and the other?

This is for a Play Framework application, though I don't think it makes a difference. Also this is for SBT v0.13, which uses Ivy for dependency management.

1 Answers

Given two classes of exactly the same fully qualified name exist on the classpath, then which one gets loaded is determined by the order they appear on the classpath. We can see the order on Compile classpath by executing

show Compile / fullClasspath

For example, say project multi1 depends on common1 and common2, then in the following scenario

sbt:multi1> show Compile / fullClasspath
[info] * Attributed(/Users/mario_galic/code/stackoverflow/sbt-multi-project-example/multi1/target/scala-2.12/classes)
[info] * Attributed(/Users/mario_galic/code/stackoverflow/sbt-multi-project-example/common2/target/scala-2.12/classes)
[info] * Attributed(/Users/mario_galic/code/stackoverflow/sbt-multi-project-example/common1/target/scala-2.12/classes)

the class form common2 will be loaded because it comes before common1 on the classpath. We can similarly check the order on the Runtime classpath

show Runtime / fullClasspath

I believe there is nothing more intelligent than the order precedence out-of-the-box.

As a side note, sbt does provide eviction warnings in the case of different versions of the same library are resolved.

Related