Creating a jar file from a Scala file

前端 未结 9 1999
忘掉有多难
忘掉有多难 2020-12-02 04:56

I\'m new to Scala and don\'t know Java. I want to create a jar file out of a simple Scala file. So I have my HelloWorld.scala, generate a HelloWorld.jar.

Manifest.m

相关标签:
9条回答
  • 2020-12-02 05:50

    I don't want to write why's and how's rather just show the solution which worked in my case (via Linux Ubuntu command line):

    1)

    mkdir scala-jar-example
    cd scala-jar-example
    

    2)

    nano Hello.scala
    object Hello extends App   {  println("Hello, world")   }
    

    3)

    nano build.sbt
    import AssemblyKeys._
    
    assemblySettings
    
    name := "MyProject"
    
    version := "1.0"
    
    scalaVersion := "2.11.0"
    

    3)

    mkdir project
    cd project 
    nano plugins.sbt
    addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.9.1")
    

    4)

    cd ../   
    sbt assembly
    

    5)

    java -jar target/target/scala-2.11/MyProject-assembly-1.0.jar
    >> Hello, world
    
    0 讨论(0)
  • 2020-12-02 05:52

    Because Scala scripts require the Scala libraries to be installed, you will have to include the Scala runtime along with your JAR.

    There are many strategies for doing this, such as jar jar, but ultimately the issue you're seeing is that the Java process you've started can't find the Scala JARs.

    For a simple stand-alone script, I'd recommend using jar jar, otherwise you should start looking at a dependency management tool, or require users to install Scala in the JDK.

    0 讨论(0)
  • 2020-12-02 05:53

    One thing which may cause a similar problem (although it's not the problem in the initial question above) is that the Java vm seems to demand that the main method returns void. In Scala we can write something like (observe the =-sign in the definition of main):

    object MainProgram {
    
      def main(args: Array[String]) = {
        new GUI(args)
      }
    }
    

    where main actually returns a GUI-object (i.e. it's not void), but the program will run nicely when we start it using the scala command.

    If we package this code into a jar-file, with MainProgram as the Main-Class, the Java vm will complain that there's no main function, since the return type of our main is not void (I find this complaint somewhat strange, since the return type is not part of the signature).

    We would have no problems if we left out the =-sign in the header of main, or if we explicitly declared it as Unit.

    0 讨论(0)
提交回复
热议问题