【问题标题】:Scala Error ImportScala 错误导入
【发布时间】:2017-06-07 12:13:50
【问题描述】:

我正在学习 Scala,我试图从不同类的 2 个脚本导入,但是,我得到一个错误,我不知道为什么。

Summer.scala 中的这个类是我尝试从 ChecksumAccumulator 类导入单例对象的地方。

import ChecksumAccumulator.calculate

object Summer{
  def main(args: Array[String]): Unit= {
    for (arg <- args)
      println(arg + " : " +  calculate(arg))
  }
}

类 ChecksumAccumulator,带有单例对象 ChecksumAccumulator。

object ChecksumAccumulator {

/*
 When a singleton object shares the same name
 with a class, it is called that class's companion object. 
*/

  private val cache = mutable.Map.empty[String, Int]

  def calculate(s: String): Int =
    if (cache.contains(s))
      cache(s)
    else {
      val acc = new ChecksumAccumulator

      //The object with the same name of the class can acces to the private members.
      //println(acc.sum)
      for (c <- s)
        acc.add(c.toByte)
      val cs = acc.checksum()
      cache += (s -> cs)
      cs
    }
    def showMap() : Unit = {
      for(base:String <- cache.keys)
        println(cache(base))
    }
//def showMap(): String = { var cadena = cache("Every value is an object.") +  " "+ cache("Every value is an object. per second time!!");  cadena  }
}

这个脚本抛出这个错误

scala Summer.scala

Summer.scala:8: error: not found: object ChecksumAccumulator import ChecksumAccumulator.calculate ^ Summer.scala:14: 错误:未找到: 值计算 println(arg + " : " + calculate(arg)) ^ 两个错误 找到了

【问题讨论】:

标签: scala


【解决方案1】:

好像是duplicated question,但我还不能将问题标记为重复,也不能评论它们。

如果这就是你的全部代码,那就意味着你错过了:

class ChecksumAccumulator { ... }

因为您正在尝试创建此类的实例:

val acc = new ChecksumAccumulator

而且仅靠以下方式是不可能实现的:

object ChecksumAccumulator { ... }

查看有关完全相同代码示例的答案。 class ChecksumAccumulator 缺少定义:

https://stackoverflow.com/a/8681616/5100014

只需确保将其粘贴到与object ChecksumAccumulator 相同的文件中

【讨论】:

  • 好的,首先,我的问题与其他问题不同,其次,我的类 class ChecksumAccumulator { ... } 没有问题,它运行完美,对象具有相同的名称类的,在 scala 中可以做,我的问题是当我想将 1 个 Scala 脚本导入另一个 Scala 脚本时。 ChecksumAccumulator 脚本运行良好。
  • 你是怎么运行的?来自 IDE 还是来自 REPL?你如何定义 ChecksumAccumulator 对象和类?在一个文件中还是在 REPL 中?
  • 它从 REPL 运行,我在一个文件中定义 ChecksumAccumulator 对象和类
  • 我询问了 REPL,因为在标准 Scala REPL 中定义伴生对象时应该小心。您可以检查是否需要:stackoverflow.com/a/29554506/5100014。但是如果你在一个文件中定义它们,这可能不是你的问题。我认为您的 REPL 没有看到该文件。也许首先你需要加载它。见stackoverflow.com/a/7385961/5100014。我不能说更多,因为我没有看到你的项目结构。对我来说,它适用于 sbt Scala 控制台。
  • 谢谢!!是的,这是错误,非常感谢,祝你有美好的一天!
猜你喜欢
  • 2012-02-06
  • 2012-08-04
  • 2020-10-18
  • 1970-01-01
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-14
相关资源
最近更新 更多