I have three files, one is hi.scala and the second is hic.scala and third is hello.scala. The codes of both are as follows:
hi.scala
package testpackage.src
package object hi {
def abs(x: Double) = if (x>=0) x else -x
def sqrt(x: Double) = {
def sqrtIter(guess: Double, x: Double): Double =
if(isGoodGuess(guess,x)) guess
else sqrtIter(improve(guess,x),x)
def isGoodGuess(guess: Double, x: Double) =
abs(guess * guess - x)/x < .0001
def improve(guess: Double, x: Double) =
(guess + x / guess)/2
sqrtIter(1.0, x)
}
}
hic.scala
package testpackage.src{
class hic {
def abs(x: Double) = if (x>=0) x else -x
def sqrt(x: Double) = {
def sqrtIter(guess: Double, x: Double): Double =
if(isGoodGuess(guess,x)) guess
else sqrtIter(improve(guess,x),x)
def isGoodGuess(guess: Double, x: Double) =
abs(guess * guess - x)/x < .0001
def improve(guess: Double, x: Double) =
(guess + x / guess)/2
sqrtIter(1.0, x)
}
}
}
hello.scala
import testpackage.src._
object hello {
def main(args: Array[String]): Unit = {
println(hi.sqrt(2)) //works fine
println(hi.abs(-2)) //works fine
println(new hic) // error: not found: type hic
println(new testpackage.src.hic) // error: type hic is not a member of package testpackage.src
}
}
I am able to access sqrt and abs methods of hi.scala file's hi object, but I am not able to instantiate an object of hic.scala file's hic class. I am not able to understand why I am not able to instantiate the object of a class within a package.
Update: As it turned out, there was not an error in the code, but in the method of execution. The code is giving and error with the following commonds (@ println(new hic) and println(new testpackage.src.hic)) -
scalac *.scala and scala hello.scala
however, the code runs fine with the following commands -
scalac *.scala and scala hello