加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为什么主要功能没有在REPL中运行?

发布时间:2020-12-16 09:03:48 所属栏目:安全 来源:网络整理
导读:这是一个简单的程序.我预计main将以解释模式运行.但是另一个物体的存在导致它什么都不做.如果QSort不存在,程序将执行. 当我在REPL中运行main时,为什么main不被调用? object MainObject{ def main(args: Array[String])={ val unsorted = List(8,3,1,4,6,5)
这是一个简单的程序.我预计main将以解释模式运行.但是另一个物体的存在导致它什么都不做.如果QSort不存在,程序将执行.

当我在REPL中运行main时,为什么main不被调用?

object MainObject{
  def main(args: Array[String])={
    val unsorted = List(8,3,1,4,6,5)
    print("hello" + unsorted toString)
    //val sorted = QSort(unsorted)
    //sorted foreach println
  }
}

//this must not be present

object QSort{
  def apply(array: List[Int]):List[Int]={
    array
  }
}

编辑:抱歉引起混淆,我正在运行脚本scala filename.scala.

解决方法

发生了什么

如果scala的参数是现有的.scala文件,它将在内存中编译并运行.当存在单个顶级对象时,将搜索主方法,并且如果找到则执行.如果不是这种情况,则顶级语句将包含在合成主方法中,而后者将被执行.

这就是删除顶级QSort对象允许运行main方法的原因.

如果你要将它扩展为一个完整的程序,我建议编译并运行(使用像sbt这样的构建工具)编译的.class文件:

scalac main.scala && scala MainObject

如果您正在编写单个文件脚本,只需删除main方法(及其对象)并在外部作用域中编写要执行的语句,如:

// qsort.scala
object QSort{
  def apply(array: List[Int]):List[Int]={
    array
  }
}

val unsorted = List(8,5)
print("hello" + unsorted toString)
val sorted = QSort(unsorted)
sorted foreach println

并运行:scala qsort.scala

一点背景

scala命令用于执行scala“脚本”(单个文件程序)和复杂的类java程序(在类路径中具有主对象和一堆类).

来自man scala:

The  scala  utility  runs  Scala code using a Java runtime environment.
   The Scala code to run is specified in one of three ways:

      1.  With no arguments specified,a Scala shell starts and reads com-
          mands interactively.

      2.  With  -howtorun:object  specified,the fully qualified name of a
          top-level Scala object may be specified.  The object should pre-
          viously have been compiled using scalac(1).

      3.  With  -howtorun:script  specified,a file containing Scala code
          may be specified.

如果没有明确指定,则从传递给脚本的参数中猜出howtorun模式.

当给定对象的完全限定名称时,scala将猜测-howtorun:object并期望路径上具有该名称的编译对象.

否则,如果scala的参数是现有的.scala文件,则猜测-howtorun:script,并如上所述选择入口点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读