Skip to content

Some suggestions about Scala script example #1133

Closed
@counter2015

Description

@counter2015

In the doc website: https://www.scala-lang.org/documentation/your-first-lines-of-scala.html

It shows a example of Scala script.

#!/usr/bin/env scala

object HelloWorld extends App {
  println("Hello, world!")
}
HelloWorld.main(args)

When I try to run it, the compiler returns a warning.

$ ./script.sh 
./script.sh:6: warning: Script has a main object but statement is disallowed
HelloWorld.main(args)
               ^
Hello, world!

In fact without HelloWorld.main(args), it can also run while has access to args

#!/usr/bin/env scala

object HelloWorld extends App {
  println(s"Hello, world! ${args.mkString}")
}
$ ./script.sh Hello, Scala Script
Hello, world! Hello,ScalaScript

On the other hand, I found another Scala shell script example

In this one I can pass Scala comand line arguement such as -feature

#!/bin/sh
exec scala -feature -deprecation "$0" "$@"
!#

object Test {
  def main(args: Array[String]): Unit = {
    implicit def strToSymbol(str: String): Symbol = Symbol(str)
    println("hello, world")
  }
}

In this way, it will show me details about warning.

$ ./test.scala 
./test.scala:7: warning: implicit conversion method strToSymbol should be enabled
by making the implicit value scala.language.implicitConversions visible.
This can be achieved by adding the import clause 'import scala.language.implicitConversions'
or by setting the compiler option -language:implicitConversions.
See the Scaladoc for value scala.language.implicitConversions for a discussion
why the feature should be explicitly enabled.
    implicit def strToSymbol(str: String): Symbol = Symbol(str)
                 ^
hello, world

In my humble opinion, I have two suggestions:

  • Remove HelloWorld.main(args) from the example since it will cause a warning.
  • Using second header of script header since it can pass command line arguements of Scala.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions