Wawrzyniec Pruski
Wawrzyniec Pruski

Reputation: 389

How can I use scala sources from a different location in a sbt project and also make it work with IntelliJ IDEA?

This project compiles and runs fine using sbt. https://github.com/stuhajbejovic/multi-project-sbt

The problem I'm having is when I open the hello.sbt project in intellij idea, it says:

cannot resolve symbol testing

when I hover over the red import statement on line 1 of hello.scala.

I also tried using this in my build.sbt:

unmanagedSourceDirectories in Compile += baseDirectory.value / "../common"

but then I get the following warning in IntelliJ and can't run the app inside IntelliJ:

These source roots cannot be included in the IDEA project model.

Solution: declare an SBT project for these sources and include the project in dependencies.

Is there a way to get IntelliJ to follow sbt configuration to where the common sources are?

Upvotes: 0

Views: 271

Answers (1)

Mike Allen
Mike Allen

Reputation: 8249

You need to use a multi-project SBT build file. That is, have one build.sbt file for the entire project. IntelliJ should honor that without a problem.

I think your build.sbt file, which should go in your project's root directory, would need to look like this:

lazy val commonSettings = Seq(
  scalaVersion := "2.12.1",
  version := "0.1"
)

lazy val common = project.in(file("sbt_testing/common")).
settings(commonSettings: _*).
settings(
  name := "common"
)

lazy val hello = project.in(file("sbt_testing/hello")).
dependsOn(common).
settings(commonSettings: _*).
settings(
  name := "Hello"
)

As you can see, you can group settings common to both projects and also ensure better consistency between them.

You will need to remove the build.sbt files in sbt_testing/common and sbt_testing/hello.

UPDATE: Corrected use of commonSettings in the SBT build.sbt file. Apologies for the confusion!

UPDATE 2: In order to run the code in the HelloWorld class, you will need to do the following (I also renamed the "root" project to "hello"):

$ sbt
[info] Loading global plugins from /home/user/.sbt/0.13/plugins
[info] Loading project definition from /home/user/src/multiSbt/project
[info] Set current project to multisbt (in build file:/home/user/src/multiSbt/)
> project hello
[info] Set current project to Hello (in build file:/home/user/src/multiSbt/)
> run
[info] Compiling 1 Scala source to 
/home/user/src/multiSbt/sbt_testing/hello/target/scala-2.12/classes...
[info] Running HelloWorld 
Hello, world!
This is from common: testing 123
[success] Total time: 3 s, completed May 1, 2017 3:27:16 PM

For more information on SBT multi-project builds, refer to the official documentation...

Upvotes: 2

Related Questions