1

I am learning scala recently, the package in scala confused me.

I have a file named StockPriceFinder.scala:

// StockPriceFinder.scala
object StockPriceFinder {
    def getTickersAndUnits() = {
        val stockAndUnitsXML = scala.xml.XML.load("stocks.xml")

        (Map[String, Int]() /: (stocksAndUnitsXML \ "symbol")) {
            (map, symbolNode) => 
                val ticker = (symbolNode \ "@ticker").toString
                val units = (symbolNode \ "units").text.toInt
                map ++ Map(ticker -> units)
        }
    }
}

then I want to use StockPriceFinder in test.scala which is in the same folder:

val symbolAndUnits = StockPriceFinder.getTickersAndUnits

but when I run it with scala test.scala, I got error:error: not found: value StockPriceFinder. In Java, if this two source files are in the same folder, I do not need to import and I can use it directly, so how can I import StockPriceFinder correctly in scala?

I have tried to use import StockPriceFinder in test.scala, but it still does not work.

2
  • possible duplicate of Scala, importing class Commented Mar 20, 2015 at 5:28
  • @LionelPort I have tried to use import StockPriceFinder in test.scala, but it still does not work Commented Mar 20, 2015 at 5:38

1 Answer 1

3

You don't need to import StockPriceFinder if the files are in the same package (not folder).

But you do need to compile StockPriceFinder.scala first and pass the correct classpath to scala.

scalac StockPriceFinder.scala
scala -cp . test.scala

should work (might be a bit off). However, you shouldn't do it manually, since it becomes unmanageable very quickly; use SBT or other build tools (Maven, Gradle).

Sign up to request clarification or add additional context in comments.

2 Comments

if I do not need StockPriceFinder, I just use scala test.scala it will run normally without compiling. So if I need to compile the file if I refer this file in some other place?
It doesn't "run without compiling", scala just takes care of compiling it for you. But it doesn't know where it should get StockPriceFinder from.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.