2

So I just started learning Scala this afternoon and quickly came to a stopping point with such exception when trying to run my program with standard scalac Sqrt.scala and scala Sqrt:

java.lang.NoSuchMethodException: Sqrt.main is not static
    at scala.reflect.internal.util.ScalaClassLoader$class.run(ScalaClassLoader.scala:68)
    at scala.reflect.internal.util.ScalaClassLoader$URLClassLoader.run(ScalaClassLoader.scala:101)
    at scala.tools.nsc.CommonRunner$class.run(ObjectRunner.scala:22)
    at scala.tools.nsc.ObjectRunner$.run(ObjectRunner.scala:39)
    at scala.tools.nsc.CommonRunner$class.runAndCatch(ObjectRunner.scala:29)
    at scala.tools.nsc.ObjectRunner$.runAndCatch(ObjectRunner.scala:39)
    at scala.tools.nsc.MainGenericRunner.runTarget$1(MainGenericRunner.scala:65)
    at scala.tools.nsc.MainGenericRunner.run$1(MainGenericRunner.scala:87)
    at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:98)
    at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:103)
    at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)

Here's the code of my Sqrt.scala:

class Sqrt {
  val PRECISION = 0.01

  def abs(d: Double): Double =
    if (d >= 0) d else -d

  def isCloseEnough(guess: Double, x: Double): Boolean =
    abs(guess * guess - x) < PRECISION

  def improve(guess: Double, x: Double): Double =
    (x/guess + guess)/2

  def iter(guess: Double, x: Double): Double =
    if(isCloseEnough(guess, x)) guess
    else iter(improve(guess, x), x)

  def sqrt(x: Double): Double =
    iter(1, x)

  def main(args: Array[String]) {
    println(sqrt(16))
  }
}

Can anyone come up with an explanation?

Cube.
  • 483
  • 6
  • 15

1 Answers1

5

object Sqrt instead of class Sqrt

Look at the Scala getting started: http://www.scala-lang.org/documentation/getting-started.html

Also, the syntax of the main function you're using is deprecated, it should be: def main(args: Array[String]):Unit = {}.

n1r3
  • 8,593
  • 3
  • 18
  • 19