在scala中导入对象时出错

时间:2013-03-28 00:12:46

标签: eclipse scala

我正在学习Scala编程。我有两个名为chapter3chapter4的包。以下是代码:

FileOperation.scala中文件chapter3的代码:

package chapter3

import scala.io.Source

object FileOperation {

  /**
   * This function determines the length of line length.
   */
  def findLineLengthWidth(line : String) : Int = {
    val len = line.length.toString.length()
    return len;
  }

  def readFile(filename : String) {
    val lines = Source.fromFile(filename).getLines().toList
    val longestLine = lines.reduceLeft((a, b) => if(a.length > b.length) a else b)
    val maxlength = findLineLengthWidth(longestLine)

    for (line <- lines) {
      val len = findLineLengthWidth(line)
      val spacecount = (maxlength - len)
      val padding = " " * spacecount
      println(padding + line.length +"|"+ line)
    }
  }
}

第4章包中的文件代码:Summer.scala

package chapter4

import chapter3.FileOperation._

object Summer {

  def main(args: Array[String]): Unit = {
    {
      //val file = new FileOperation
      readFile("abc.txt")
    } 
  }
}

当我在Eclipse中运行此代码时,它工作正常。但是,当我尝试在终端中编译它时,我收到以下错误:

$ scalac *.scala
Summer.scala:3: error: not found: object chapter3
import chapter3.FileOperation._
       ^
Summer.scala:11: error: not found: value readFile
      readFile("abc.txt")
      ^
two errors found

1 个答案:

答案 0 :(得分:1)

确保您的目录结构为:

chapter3/FileOperation.scala
chapter4/Summer.scala

然后,从父目录运行:

scalac chapter3/FileOperation.scala chapter4/Summer.scala

这个编译得很好。如果您想单独编译它们,请确保FileOperation是第一个,因为Summer取决于它。

编译完成后,您可以使用以下命令运行它:

scala -cp .:chapter3:chapter4 chapter4.Summer