0

I want to import classes in one project to the other project in scala multi-project.

Now My project structure:

Project
ᄂ project1
│    ᄂ src
│       ᄂ main
│          ᄂ scala
│             ᄂ com.foo1.bar
│                ᄂ aaa
│                   ᄂ aaa1.scala
ᄂ project2
    ᄂ src
       ᄂ main
          ᄂ scala
             ᄂ com.foo2.bar
                ᄂ bbb
                   ᄂ bbb1.scala

bbb1.scala :

class bbb1() {
    def bFunction() = {
       // some function
    }
}

In this case, I want to import bbb1 in aaa1.scala file like below:

aaa1.scala

import com.foo2.bar.bbb._

class aaa1() {
    def aFunction() = {
        val t = bFunction()
    }
}

I set the build.sbt dependsOn(). But IDE highlight the import com.foo2.bar.bbb._ is wrong. And If I run some test code, error raise.

I use IntelliJ and scala 2.12.12.

coder mate
  • 15
  • 3

1 Answers1

2

(Just for future readers, the beginning was here: How to packaging specific directory in scala?)

Your build.sbt should be

lazy val project1 = project
  .dependsOn(project2)

lazy val project2 = project

Don't forget to re-import the project in IDE.

Don't forget package declarations package ... in your sources

project1/src/main/scala/com/foo1/bar/aaa/aaa1.scala

package com.foo1.bar.aaa  // <-- !!!

import com.foo2.bar.bbb._

class aaa1() {
  def aFunction() = {
    val t = new bbb1().bFunction()
  }
}

project2/src/main/scala/com/foo2/bar/bbb/bbb1.scala

package com.foo2.bar.bbb  // <-- !!!

class bbb1() {
  def bFunction() = {
    // some function
  }
}

Packages and subprojects are different concepts: Why can't sbt/assembly find the main classes in a project with multiple subprojects?

Please notice that if bbb1 is a class rather than object then you should call bFunction on some instance, e.g. new bbb1().bFunction().

Sbt documentation: https://www.scala-sbt.org/1.x/docs/Multi-Project.html

While confused, you should rely on sbt clean, sbt compile, sbt run, sbt test rather than IntelliJ functionality (Ctrl+Alt+F10 etc.).

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66