I'm developing a Scala package using an sbt project scheme through IntelliJ. I wanted to use the classes in this package in the Scala REPL, so I followed the instructions in this post. Namely,
- Navigate to where my package's source files are located (MyProject/src/main/scala/mypackage)
- Run "sbt compile"
- Navigate to where sbt stores the compiled source files (MyProject/src/main/scala/mypackage/target/scala-2.12/classes/mytest)
- Run "scala -cp ."
This all works fine until I try to create an instance of one of my package's classes and I get the error MyClass does not have a constructor. However, if I just paste the class definitions into the Scala REPL, I can create instances with no errors. What am I doing wrong here?
As a reproducible example, I created a package mytest with two files TraitOne.scala and ClassOne.scala. The first file looks like
package mytest
trait TraitOne {
val a: Double
def aMinus(x: Double): Double = a - x
}
The second file looks like
package mytest
class ClassOne(val a: Double) extends TraitOne {
def aPlus(x: Double): Double = a + x
}
If I follow steps 1 - 4 as listed above and write val temp = new ClassOne(1.0), I get the error ClassOne does not have a constructor. But if I paste
trait TraitOne {
val a: Double
def aMinus(x: Double): Double = a - x
}
class ClassOne(val a: Double) extends TraitOne {
def aPlus(x: Double): Double = a + x
}
into the REPL, val temp = new ClassOne(1.0) works fine.
sbt console? Or, if you want to use those classes on other environments, trysbt packageto generate a single JAR with all your classes, and then pass that JAR to thecpargument. - Luis Miguel Mejía SuárezMyProject/src/main/scala/mypackageand runningsbt package. This was successful, and a.jarfile appeared atMyProject/src/main/scala/mypackage/target/scala-2.12/classes/mypackage_2.12-0.1.0-SNAPSHOT.jar. However, when I runscala -cp pathtojar, neitherimport mypackagenorval temp = new ClassOne(1.0)work. Any thoughts? - zacksbt console. If you want to distribute your classes to other users, there are other alternatives. - Luis Miguel Mejía Suárezsbt consolefrom withinMyProjectand it worked! Thanks so much for your advice. - zacksbt consoleworked and somehow I understood that it didn't work. I am glad it helped. I deleted my last comment (since it doesn't make sense anymore) I would suggest you do the same with your last comment since it is off-topic to the site right now. - Luis Miguel Mejía Suárez