Reputation: 17617
I am trying to use apache math with scala but I am not able to run the examples from the documentation http://commons.apache.org/proper/commons-math/userguide/random.html
import math._
object Hello extends App {
println("HELLO")
RandomDataGenerator randomData = new RandomDataGenerator();
//not found: value RandomDataGenerator
}
I am new to scala and java so please provide a detailed answer.
EDIT:
I have created a new folder with the build.sbt
. If I run the command sbt console
in that folder than the code seems to be working in the console.
But now how can I can run the code on eclipse??
Upvotes: 3
Views: 2920
Reputation: 139038
Apache project documentation tends to be terrible about explaining how to get started. For example, you'll see "Download" links everywhere that show you how to get the project code and jars. Don't do this! Use a proper build system that will manage your dependencies for you. For this example I'll use SBT, but Maven would work just as well (although with a lot more verbosity).
Once you've got SBT installed you can search Maven Central for "commons-math", which will take you here. You'll see a "Scala SBT" button on the side; click it and copy the text to a file called build.sbt
:
libraryDependencies += "org.apache.commons" % "commons-math3" % "3.3"
Okay, now you can start an SBT console with sbt console
. Now you need to know the full path to the class you want, which of course is nowhere to be found in the Apache documentation, because that would be too convenient. With a little bit of Googling you'll find the following:
import org.apache.commons.math3.random.RandomDataGenerator
And now you can create an instance:
object Hello extends App {
println("HELLO")
val randomData = new RandomDataGenerator()
println(randomData.nextLong(0, 100))
}
And you're done! Now any good Scala resource will give you an idea of how to accomplish whatever you want to do next.
Upvotes: 13
Reputation: 12104
First of all, you might want to look up Scala's general syntactic rules, unlike Java for example, Scala doesn't start its variables with the type, nor is a semicolon required..
// Java:
int a = 5;
int b = 6;
System.out.println(a + b);
// Scala:
val a = 5
val b = 6
println(a + b)
So in case of your "problem", the solution is really just
val randomData = new RandomDataGenerator // empty parentheses can be omitted
That, and your import might be wrong, since RandomDataGenerator
is under org.apache.commons.math3.random.RandomDataGenerator
, not math
Upvotes: 0