How to import files from other directory in Scala?
I have dir hierarchy such as this:
src
src/Model
src/View
src/Controller
Now I want to built my application. How can I import/include classes from Model View and Controller, becouse compiler can't see them?
// edit
src/App.scala
import swing._
object App extends Application {
val model = new Model
val view = new View(model)
val controller = new Controller(model, view)
view.visible = true
}
src/Model/Model.scala
class Model {
// some code
}
src/View/View.scala
import swing._
class View(model:Model) extends MainFrame {
// some code
}
src/Controller/Controller.scala
class Controller(model:M开发者_如何转开发odel, view:View) {
// some code
}
Here is a build script
#!/bin/bash
source ${0%/*}/config.inc.sh
if [ ! -d $CLASSES_PATH ]; then
notice "Creating classes directory..."
mkdir $CLASSES_PATH
fi
notice "Building VirtualCut..."
scalac $SOURCE_PATH/Model/*.scala -d $CLASSES_PATH || error "Build failed (Model)."
scalac $SOURCE_PATH/View/*.scala -d $CLASSES_PATH || error "Build failed (View)."
scalac $SOURCE_PATH/Controller/*.scala -d $CLASSES_PATH || error "Build failed (Controller)."
scalac $SOURCE_PATH/*.scala -d $CLASSES_PATH || error "Build failed."
success "Building complete."
exit 0
Everything works fine when all files are in src dir.
Use a grown up build tool, instead of messing around with hand-rolled shell scripts. SBT has got to be your best bet here.
At the top of each source file, specify what package it should belong in. It's ill-advised to just dump everything in the default package - a guaranteed recipe for future namespace conflicts.
Make sure that each file also
import
s classes that it has a dependency on.
Since you have not reported what error you are getting, we are left to guess. However, the basic error seems to be simply that you are compiling code that reference each other in different steps. The solution is simple: don't do that. Do this:
scalac $SOURCE_PATH/Model/*.scala $SOURCE_PATH/View/*.scala $SOURCE_PATH/Controller/*.scala $SOURCE_PATH/*.scala -d $CLASSES_PATH || error "Build failed."
success "Building complete."
If, however, you are sure there are no cross dependencies, you need to pass the CLASSES_PATH as classpath:
scalac $SOURCE_PATH/Model/*.scala-d $CLASSES_PATH || error "Build failed (Model)."
scalac $SOURCE_PATH/View/*.scala -cp $CLASSES_PATH -d $CLASSES_PATH || error "Build failed (View)."
scalac $SOURCE_PATH/Controller/*.scala -cp $CLASSES_PATH -d $CLASSES_PATH || error "Build failed (Controller)."
scalac $SOURCE_PATH/*.scala -cp $CLASSES_PATH -d $CLASSES_PATH || error "Build failed."
精彩评论