I'm a Haskeller looking into Scala. I'm meeting frustration not with code, but with imports/packages.
I have two files, Test.scala
and Lists.scala
.
// Lists.scala
package problems
object Lists {
def last(list: List[Any]): Option[Any] = list match {
case Nil => None
case x :: Nil => Some(x)
case _ :: xs => last(xs)
}
}
And:
// Test.scala
import problems._
object Test extends App {
println("Starting tests...")
println(last(List(1,2,3,4,5)))
}
Test.scala
does not compile. Running scalac Test.scala Lists.scala
yields:
Test.scala:5: error: not found: value last
println(last(List(1,2,3,4,5))
Yet rewriting last
as Lists.last
makes it succeed. Doesn't that defeat the point of the import problems._
wildcard? I notice that math functions can be written without a preceeding math.
by doing import math._
. Why won't this work for my files as well?
Real aim: I just want to be able to make a package, then easily test its functions with println
in another file. What's the best way to do that? Can I not do away with the object {...}
in Test.scala
and just run it with scala
, forgoing the compilation process?
Doesn't that defeat the point of the import problems._ wildcard?
No, it does not. By using the wildcard you're bringing all the classes/objects in that package into the scope, but not their contents.
I notice that math functions can be written without a preceding
math.
by doingimport math._
Why won't this work for my files as well?
It will work, but you need a proper import: import problems.Lists._
. Otherwise you can place your functions into a package object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With