How can I use apache math with scala?

I am trying to use apache math with scala but I cannot run 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 give a detailed answer.

EDIT: I created a new folder with build.sbt

. If I run the command sbt console

in that folder than the code seems to work in the console. But now how can I run the code on eclipse ??

+3


source to share


2 answers


The Apache project documentation is generally terrible at explaining how to get started. For example, you will see Download links all over the world that show you how to get the project and jar code. Do not do this! Use the correct build system to manage your dependencies for you. For this example, I'll be using SBT , but Maven will work just as well (albeit with much more detail).

Once you have SBT installed, you can find Maven Central for "commons-math" which will take you here . You will see a "Scala SBT" button on the side; click it and copy the text to a file named build.sbt

:

libraryDependencies += "org.apache.commons" % "commons-math3" % "3.3"

      

Ok, now you can start the SBT console with sbt console

. Now you need to know the full path to the class you want, which of course is not found anywhere in the Apache documentation because that would be too handy. With a little Googling, you will 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 what you want to do next.

+10


source


First of all, you can look for general Scala syntax rules, unlike Java, for example Scala does not run its variables with a type, and no semicolon is 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 simple



val randomData = new RandomDataGenerator // empty parentheses can be omitted 

      

This, and your import might be wrong as it RandomDataGenerator

is under org.apache.commons.math3.random.RandomDataGenerator

and notmath

0


source







All Articles