I could not run a Scala project from command prompt. It was able to get it to work when I wrote the program in Scala Worksheet, but I want to get it to run from Eclipse using CMD. I did:
C:\WINDOWS\System32>scalac Hello_WORLD.scala
error: source file 'Hello_WORLD.scala' could not be found
one error found
Then, I tried to skip the compiling and go straight to the execution:
C:\WINDOWS\system32>scala Hello_WORLD
No such file or class on classpath: Hello_WORLD
Here is my code that I wrote in Eclipse. I created a Scala Project and a Scala class within the src folder.
class Hello_WORLD {
def main(args: Array[String]){
println("HELLO!")
}
}
Can you please help me? Please try not to leave rude comments. This is my first time trying out Scala. I would greatly appreciate your help. I tried looking at the Scala documentation and other posts on StackOverflow, but none of them helped my situation. I made sure that the environment variables were configured correctly. If you need any more information, please let me know in the comments.
Regards,
Ani
There's an option in Eclipse:
From the Package Explorer tab -> Select the project src directory -> Right click -> New -> Scala Application
From File -> New -> Scala Application
Choosing one of those for the default package, lets me create this:
object HelloWorld extends App {
println( "Hello World")
}
Notice that the "main" comes from extending App. It's an object instead of a class and you can run it inside of Eclipse via:
Choosing it in the Package Explorer -> right click -> Run As -> Scala Application
Run -> Run Configurations -> Scala Applications -> New -> Hello World -> Run
If you want to run that from the command line, you can Export your code to a jar file using:
Package Explorer tab -> right click -> Java -> Jar file -> browse to choose the name/location of the Jar file.
Here is all steps you have to take:
1- Install Scala and make sure the path is included in the windows path variable.( to check it, type scala in terminal, it should go to scala console
2- cd to directory with HellWorld.scala
3- the code should be this:
object HelloWorld extends App{
println("Hello World!")
}
4- scalac Helloworld.scala
it should work.
A scala programm needs a main class to work like java but if u dont want to define a "main" then you can go for "object" with extending "App". This will work fine. In this case you will not asked to have a "main" class.
object FirstProg extends App {
println("My first prog...!")
}
Related
I am trying to run a scala project for the first time in eclipse. I have selected "Scala" in perspective. I am having trouble with configuring my run for scala.
My project name is scala_try and in the project folder I have:
src -> scala_try -> Demo.scala
When I right-click on Demo.scala and try to run it, I have:
Run As -> Run Configurations...
How do I configure my run for scala here?
I tried: Scala-Application -> New_configuration but when I search for Main Class, there is nothing matched.
If I just go on and write Demo as Main class, after running I get this error:
Error: Could not find or load main class Main
Caused by: java.lang.ClassNotFoundException: Main
my code in Demo.scala:
package scala_try
object Demo extends App{
def main(args: Array[String]) {
print("Hola!");
}
}
Any sort of help would be highly appreciated. Thanks in advance!
Just try removing either of these code
package scala_try
object Demo {
def main(args: Array[String]) {
print("Hola!");
}
}
OR
package scala_try
object Demo extends App{
print("Hola!");
}
Using extends App and main method together in a object generally causes this issue as per my opinion.
I've recently installed Scala as a part of my functional programming course and I've encountered a problem: IntelliJ IDEA 2017.2.1 (Java version 9, build 9+181) doesn't run any of my scala code, exitting with
Error: Could not find or load main class Main
This code is an example.
object Main {
def length[A](list:List[A]):Int = {
if (list == Nil) 0
else 1 + length(list.tail)
}
def main(args: Array[String]): Unit = {
length(List[Int](1, 4, 5, 12, -1))
}
}
It's really simple, yet IntelliJ refuses to run it. Windows CMD doesn't even react to a scala command, resulting into
'scala' is not recognized as an internal or external command,
operable program or batch file.
even though I have it installed on my computer. If I call Scala Console inside of IntelliJ everything works fine and compiles as expected. I've tried switching to JDK 1.8 inside of IntelliJ, yet it led to no result.
What could be the problem?
For me it turns out that the src/main was not marked as Sources Root
which causes the following error
...
One of the two will be used. Which one is undefined.
Error: Could not find or load main class Main
Process finished with exit code 1
So of course after I mark the src/main as Sources Root, the Scala Hello World example runs happy again.
Notice the blue color of directory src/main when it's marked as Sources Root
Are you using the little green arrow to run the program from inside of your Main object?
How did you create the program? It could be that your build file SBT configuration of the project is a different Scala version than what's installed on your computer.
It's really simple, yet IntelliJ refuses to run it. Windows CMD
doesn't even react to a scala command, resulting into
'scala' is not recognized as an internal or external command, operable program or batch file.
This means that Scala is not added to your class path in your terminal. Look up how to do that and see if that doesn't help out your IntelliJ problem too.
New to Scala and having problems reading an XML file in a Scala worksheet. So far I have:
downloaded the Scala IDE (for Windows) and unzipped it to my C:\ drive
created a Scala project with the following file path: C:\eclipse\workspace\xml_data
created the xml file ...\xml_data\music.xml using the following data
created a package sample_data and create the following object (with file path: ...\xml_data\src\sample_data\SampleData.scala):
package sample_data
import scala.xml.XML
object SampleData {
val data = XML.loadFile("music.xml")
}
object PrintSampleData extends Application {
println(SampleData.data)
}
This runs OK, however, when I create the Scala worksheet test_sample_data.sc:
import sample_data.SampleData
object test {
println(SampleData.data)
}
I get a java.lang.ExceptionInInitializerError which includes: Caused by: java.io.FileNotFoundException: music.xml (The system cannot find the file specified).
The workspace is C:\eclipse\workspace. Any help or insight much appreciated. Cheers!
UPDATE:
Following aepurniet's advice, I ran new java.io.File(".").getAbsolutePath() and got the following respectively:
SampleData.scala: C:\eclipse\workspace\xml_data\.
test_sample_data.sc: C:\eclipse\.
So this is what is causing the problem. Does anyone know why this occurs? Absolute file paths resolve the problem. Is this the best solution?
Regarding what is causing different user directory between the scala class and worksheet:
You are likely hitting the Eclipse IDE issue listed here
https://github.com/scala-ide/scala-worksheet/issues/102
Jfyi, I used Intellij and the issue is not reproducible there.
Regarding using absolute paths:
Using absolute path works fine for quick testing, but would NOT be a good practice for the actual implementation. You can consider passing the path along with the filename as input to SampleData.
Some hack mentioned here to get the base path of the workspace from the scala worksheet: Configure working directory of Scala worksheet
If this is just for your testing, hacking the absolute path of workspace inside the worksheets might be the easiest for you.
SampleData.scala
package sample_data
import scala.xml.XML
object SampleData {
def data(filename: String) = XML.loadFile(filename)
}
object PrintSampleData extends Application {
println(SampleData.data(System.getProperty("user.dir") + "/music.xml")
}
Scala worksheet:
import sample_data.SampleData
object test {
val workDir = ... // Using the hack or hardcoding
println(SampleData.data(workDir + "/music.xml"))
}
I'm developing an application on Eclipse with Scala and a would like to create a .jar. I have found tuto to do that, but it use the package scala.tools.nsc and I don't know where I can found this thing.
I have tried too, to generate the .class and then with the command jar cmf .... to generate the .jar but when I launch the .jar an error occur. (NoClassFound)
With sbt I have tried too, but when I compile my project that work with eclipse a lot of error appear.
Somebody can me explain how I can simply create a .jar with Eclipse or another tools.
Eclipse has a build-in option to generate runnable jars, but it is well hidden. Also it does not recognize Scala's main() signatures, so you will have to create a Java class with a main() method.
Create a Java class with a main() method which simply forwards the call to your Scala code.
Then right click on your newly created Java class and select: Run As -> Java Application.
This will create a runnable configuration which will later be used as a part of your runnable jar.
Now you are ready to dig out the runnable jar option from the Eclipse's menu:
File -> Export -> Java -> Runnable JAR file
In the presented dialog select the Launch Configuration you have created earlier (in step2), name your jar (myapp.jar), select your dependency export options and click finish.
The jar will be created in the Eclipse's workspace by default.
Run the jar using the line: scala myapp.jar
Your question about missing images: Eclipse requires a manual refresh when files are added or removed. Right click on your project and select Refresh.
This concludes the tutorial on the highly intuitive Eclipse interface.
Note: Instructions for Eclipse version 3.6.2.
Jars
When you create a jar out of your classes, possibly the dependencies are not included in that jar. When running that jar, you need to put the jars containing the dependencies on the classpath (with the -cp switch to java). Most important dependency is the scala-library jar. Of course knowing what is not found by NoClassDefFound would help.
Sbt
When building with sbt, maybe it is missing dependencies that you have manually added to the Eclipse project? (Note: I did not use sbt).
Maven
I found the clearest and most painless way is to go with maven alone, or possibly maven + Intellij Idea (community edition is free) + Scala Plugin. Works very smooth.
For maven, you need to adapt the available scala archetype a bit since the libraries it refers to are not the most recent version, but apart from that it is very fine.
Here is a pom.xml I'm using: https://gist.github.com/1096870
Use the standard maven folder structure (source root is src/main/scala) and then mvn package creates the jar fine.
Use the below steps for time being .But this is not the full time solution.Better to go for sbt build jar for Spark-Scala combination.
Temporary solution using java class ,calling the scala main class.
MainClass.java
public class MainClass {
public static void main(String[] args) {
SampleApp app=new SampleApp();
app.main(args); }
}
SampleApp.scala
class SampleApp {
def main(args: Array[String]) {
println("First Scala SampleApp")}
}
Export it as a jar by using normal java jar export by choosing the MainClass main method.
name the jar file as Sample.jar
Run it in the Cluster using below command.
/spark/bin/spark-submit --class com.scala.MainClass SampleScala.jar
The output you can get as:
First Scala SampleApp
% cat a.scala
package foo
object Whee {
def main(args: Array[String]): Unit = {
println("I'm in a jar")
}
}
% scalac29 -d whee.jar a.scala
% scala29 -cp whee.jar foo.Whee
I'm in a jar
%
To build off of what #Kumar Basapuram wrote:
Make a java class called "Wrapper.java".
package animals;
public class Wrapper {
public static void main(String[] args) {
SampleApp app=new SampleApp();
app.main(args);
}
}
Link this main method to the main method in the "SampleApp.scala" class.
package animals
class SampleApp {
def main(args: Array[String]){
var c = new Cow("Bessie", 100)
println(c.speak)
var h = new Horse("CJ", 50)
println(h.speak)
var s = new Sheep("Little Lamb", 25)
println(s.speak)
println(s.weigh)
println(h.weigh)
println(c.weigh)
}
}
Project with Java and Scala Classes Picture
Right Click on the Project ScalaPracticeCreation.
Click Export...
Click Runnable JAR file under the Java folder
Exporting Scala Class into a jar Executable Picture
Click Next >
Select Wrapper - ScalaPracticeCreations
Select Export destination to a place on your computer
Select "Extract required libraries into generated JAR" under the "Library
handling:" option
Click Finish
Run the file through the Eclipse IDE and it works.
Run it through the Command Prompt and it does not work.
Command Prompt Picture
To fix this remove the println methods from the "SampleApp.scala".
package animals
class SampleApp {
def main(args: Array[String]) {
var c = new Cow("Bessie", 100)
var h = new Horse("CJ", 50)
var s = new Sheep("Little Lamb", 25)
c.weigh().toString()
}
}
add "System.out.println(app.main(args));" to replace "app.main(args);" in the Wrapper.java class
package animals;
public class Wrapper {
public static void main(String[] args) {
SampleApp app=new SampleApp();
System.out.println(app.main(args));
}
}
Now reexport the program after running it.
success in the command prompt Picture
Now it works.
Here are the extra filler .scala classes. Note that the Demo.scala class is irrelevant.
Weight.scala:
package animals
abstract class Weight(size: Int) {
def weigh = "My size is " + size
}
Animal.scala:
package animals
abstract class Animal(name: String, weight: Int) extends Weight(weight){
def speak = name + " says " + sound
def sound: String
override def weigh() = "My name is " + name + " and I weigh: " + weight
}
Cow.scala:
package animals
class Cow (name: String, weight: Int) extends Animal(name,weight){
override def sound() = "mooooo"
}
Horse.scala:
package animals
class Horse (name: String, weight: Int) extends Animal(name,weight){
override def sound() = "neigh"
}
Sheep.scala:
package animals
class Sheep (name: String, weight: Int) extends Animal(name,weight) {
override def sound() = "baaaa"
}
Note that this may not be the best solution although it is a functional solution. Scala sbt may be a better solution: Scala sbt or this Scala sbt-assembly.
I have installed Eclipse 3.5.2 and today's Scala plugin from /update-current (that's Scala 2.8 final.) I can compile and run Scala projects consisting of a single singleton object that implements main().
But, if a project contains more classes, I receive the "Could not find the main class" error.
I have tried searching for the solution and I discovered:
Eclipse is correctly looking for the Main$ class, not the Main class
* under Debug Configurations, my main class is correctly identified as mypackage.Main
* my plugin is up to date and recommended for my version of Eclipse
* cleaning, restarting etc. doesn't help.
The same project will compile with scalac.
Thanks for any ideas on how to solve this.
EDIT: MatthieuF suggested I should post the code.
This snippet produces an error. It's not the most idiomatic code, but I wrote it that way to test my environment. I tried it as a single file and as separate files. It DOES work with scalac.
import swing._
class HelloFrame extends Frame {
title = "First program"
contents = new Label("Hello, world!")
}
object Hello {
val frame = new HelloFrame
def main(args : Array[String]) : Unit = {
frame.visible = true
}
}
BUT, if I nest the definition of HelloFrame within Hello, it works. This snippet runs perfectly:
import swing._
object Hello {
class HelloFrame extends Frame {
title = "First program"
contents = new Label("Hello, world!")
}
val frame = new HelloFrame
def main(args : Array[String]) : Unit = {
frame.visible = true
}
}
For me, the problem was that there was a build error (see Problems tab) which was preventing compilation; oops! The reason you see the error is that the run macro proceeds despite the failed compilation step, and attempts to run class files it expects to be there; they don't exist because there was a build error preventing compilation, so it says it can't find Main (not compiled).
Problem goes away when build can complete successfully, i.e. errors are fixed.
I guess, theoretically, there may be more complicated reasons your build is not completing successfully that are not listed in Problems.
One possibility is that you are trying to launch using ctrl-F11, but from a different class.
The Scala Eclipse plugin does not obey the defaults for Java launching. In Preferences->Run/Debug->Launching, there are some options Launch Operation->Always Launch the previously selected application, etc. This currently does not work in the Scala eclipse plugin. To launch a specified main, you need to launch it from the editor for the class.
There has been a bug raised for this. http://scala-ide.assembla.com/spaces/scala-ide/tickets/1000023-scala-launch--does-not-follow-jdt-behaviour
EDIT: This is now (mostly) fixed.
For me it was Eclipse specific problem. I noticed that .class file wasn't built at all. So bin directory doesn't have compiled classes.
When I manually compiled *.scala file using *.sbt and copied it to bin directory it was working as expected.
I tried different tips and tricks and it wasn't worked until I reinstalled Scala plugin in Eclipse .
I'd solve similar problem by executig "Project->Clean.." with next automatically building.
I had the same error message with a Java application made by myself.
The problem was that I deleted (though inside Eclipse) a jar that belonged to the Java build path, without deleting it from the Java build path (project's Properties window). When I did it the class could compile and run again.
Make sure that the .class files exist, usually below the bin directory.
In particular, if you have errors in unrelated files in the same project then the compilation may fail, and no .class files will be produced.
There can be the case of projects, containing errors, added to the build path of the application which prevents the completion of successful compilation. Make sure you remove any such project from the build path before running the application.
Removing these projects solved the problem for me.
Do you have a proper build tool setup? Like sbt have you installed it?
You can check its version by $sbt --version
If it is not setup you can download from here http://www.scala-sbt.org/download.html
You might have to restart your eclipse after installation.
Just copy your XXX.scala file code. Remove the package and create a new Scala Class. Paste your XXX.scala code. (If you are using maven, do a maven clean and build.) Run configuration again. This works for me.
I have faced this issue. I have just deleted the package name, created scala class, Written the same code, Set Build to "Build Automatically". Finally, It works perfectly fine.
Check scala-ide.log
For me the issue was that there were errors on:
AppData\Local\Temp\sbt_10d322fb\xsbt\ClassName.scala:16: error: not found: value enteringPhase
enteringPhase(currentRun.flattenPhase.next) { s fullName separator }
If you are using Intellij, mark directory as source root