81

Upon sbt run I have multiple choices of main class.

I would like to set a main class so I've writen in build.sbt:

mainClass := Some("aMainClass")

But sbt fails with:

build.sbt:1: error: not found: value aMainClass

I've also tried with project/Project.scala file :

import sbt._
  class ExecutableProject(info: ProjectInfo) extends DefaultProject(info)  {
  override def mainClass = Some("aMainClass")
}

error :

 project/Project.scala:3: not found: type aMainClass

How to set the main class in a build?

Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
user312728
  • 981
  • 1
  • 7
  • 7

3 Answers3

110

The main Class must be fully qualified with the package:

Compile/mainClass := Some("myPackage.aMainClass")

This will work for run and it will set the Main-Class in the Manifest when using the package task. The main class for these tasks can be set separately as in:

mainClass in (Compile, run) := Some("myPackage.aMainClass")
mainClass in (Compile, packageBin) := Some("myPackage.anotherMainClass")

Note:

mainClass := Some("myPackage.aMainClass")

does nothing. If you put this in your build file you will receive no warning that it does nothing.

Rich Oliver
  • 6,001
  • 4
  • 34
  • 57
23

As far as I know, sbt expects here a fully qualified class/object name within your project. For example, if your main class is like this:

package prog

object Main extends App {
    // Hic sunt dracones
}

then you would have to give your main class like this:

mainClass := Some("prog.Main")

You get a type error because that type is not simply found.

Lanbo
  • 15,118
  • 16
  • 70
  • 147
  • 15
    Using SBT 0.11.2 I found I had to set the main class in the compile and runtime scopes: `mainClass in (Compile, run) := Some("prog.Main")` – Richard Dallaway Jan 17 '12 at 17:56
1

My sbt version is sbt 1.5.4 (Ubuntu Java 11.0.11).

And I find mainClass in (Compile, run) :=Some("Hello") doesn't work in my build.sbt.

I finally find the offical example for 1.x version in here

// set the main class for packaging the main jar
// 'run' will still auto-detect and prompt
// change Compile to Test to set it for the test jar
Compile / packageBin / mainClass := Some("myproject.MyMain"),

// set the main class for the main 'run' task
// change Compile to Test to set it for 'test:run'
Compile / run / mainClass := Some("myproject.MyMain"),

you can add it to your settings. It works for me.

But I don't know how to integrate those commands into one.

Yi Wang
  • 81
  • 1
  • 1
  • 4
  • And [this solution](https://stackoverflow.com/questions/7674615/sbt-start-a-command-line-run-of-the-main-class-of-a-non-default-project) also works in interactive mode. – Yi Wang Dec 30 '21 at 03:41