Mika16 Mika16 - 3 months ago 15
Scala Question

Gradle fails when executes run task for scala

I created a

HelloWorld
app and I was able to execute build task but fail to execute run task.
I got the following error:


Could not find or load main class Demo


The following is my build.gradle file:

apply plugin: 'scala'
repositories{
mavenCentral()
mavenLocal()
}
dependencies{
compile 'org.slf4j:slf4j-api:1.7.5'
compile "org.scala-lang:scala-library:2.11.2"
testCompile "junit:junit:4.11"
}
task run(type: JavaExec, dependsOn: classes) {
main = 'Demo'
}


My source code Demo.scala:

object Demo {
def main(args: Array[String]) {
println("Helo World")
}
}


My file structure:

build
src\main\scala\Demo.scala
build.gradle


I am using gradle 3.0 and Java 1.8.0_91.
It looks to me that I am missing some settings related to classpath.
Any help will be appreciated.

Answer

You need to provide the classpath as well. Change run task declaration to:

task run(type: JavaExec, dependsOn: classes) {
   main = 'Demo'
   classpath = sourceSets.main.runtimeClasspath
}

And it will work fine. Demo.

To print the classpath:

task run(type: JavaExec, dependsOn: classes) {
    main = 'Demo'
    classpath = sourceSets.main.runtimeClasspath
    doFirst {
      classpath.each { println it }
    }
}