我用 Scala 和 SBT 构建了一个小型测试 jar。如果我将类路径参数放在 Scala REPL 命令行上,它会完美导入该包。但是,如果我进入 shell 然后添加类路径,它无法识别导入。作为 Scala 新手,这让我很困惑,所以我希望有人能解释一下。我会尽力提供足够的信息,但又不会太过分。
scala -cp configparser_2.10-1.0.jar
Welcome to Scala version 2.10.4 (OpenJDK 64-Bit Server VM, Java 1.7.0_75).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import com.oaktreepeak.util._
import com.oaktreepeak.util._
scala> val c = new OakConfig()
c: com.oaktreepeak.util.OakConfig = com.oaktreepeak.util.OakConfig@58d9a418
现在我将等待并在进入 shell 后将类路径加载到 jar 中:
scala
Welcome to Scala version 2.10.4 (OpenJDK 64-Bit Server VM, Java 1.7.0_75).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :cp configparser_2.10-1.0.jar
Added '/home/*****/Dyn/projects/DynECT2/scala/common/ConfigParser/test-configs/configparser_2.10-1.0.jar'. Your new classpath is:
".:/home/*****/Dyn/projects/DynECT2/scala/common/ConfigParser/test-configs/configparser_2.10-1.0.jar"
Nothing to replay.
scala> import com.oaktreepeak.util._
<console>:7: error: object oaktreepeak is not a member of package com
import com.oaktreepeak.util._
^
scala>
这是我的 build.sbt 文件:
name := "ConfigParser"
version := "1.0"
scalaVersion := "2.10.4"
organization := "com.oaktreepeak"
以及单个 Scala 源文件:
package com.oaktreepeak.util
import scala.io._
import scala.util.parsing.json._
class OakConfig {
var iRollupAfter: Int = -1;
def Load(sPath: String) {
val config = Source.fromFile(sPath).mkString
val json:Option[Any] =JSON.parseFull(config)
val map:Map[String,Any] = json.get.asInstanceOf[Map[String, Any]]
iRollupAfter = map.get("RollupAfter").get.asInstanceOf[Double].toInt
}
}
有人有什么想法或解释吗?
谢谢
最佳答案
:cp
在 Scala 2.10 中被破坏,并在 Scala 2.11 中被(有效的):require
取代。
如果您是 Scala 新手,我建议您使用最新、稳定的 Scala 版本,目前为 2.11.6。
此外,由于您是 Scala 新手,如果您想在 sbt 的 REPL(这是一个很棒的工作流程)中尝试项目中的内容,只需运行 console
,它将编译您的代码并为您提供包含所有 Scala 类、您的项目类以及所有依赖项的类的 REPL!无需手动向 REPL 提供类路径。
关于Scala sbt jar 允许在命令行上传递类路径时导入,但不能在 REPL 中导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30517211/