Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-07 15:21:24 Viewed : 42790
1.
Basic
“Hello ” program of scala
1.1. one way to write with main method
Scala is a general-purpose programming
language providing support for both object-oriented programming and functional
programming.
def defines a method.
Compile: The scalac
command compiles one (or more) Scala source
file(s) and generates Java bytecode which can be executed on any standard JVM. The Scala compiler works similarly to javac
, the Java
compiler of the Java SDK.
> scalac HelloWorld.scala
Execute: The scala
command
executes the generated bytecode with the appropriate options:
> scala
HelloWorld
Example:
Following example illustrates how we can print “Hello Scala”
with main method.
Save the file as − HellowWorld.scala.
HelloWorld.scala //File
name
package runnerdev
object HelloWorld {
def main(args: Array[String]) {
println("Hello Scala")
}
}
compile
and run the above example as follows
scala> scalac HelloWorld.scala
scala> scala
HelloWorld
Output:
Hello Scala
1.2. second way to write with out main method
Another way to write that no need to
define the main method but extends App
The App trait can be used to quickly turn objects into
executable programs. Here is an example:
object Main
extends App {
println("Hello
World: " + (args
mkString ", "))
}
Here, object Main
inherits the main
method of App
.
args
returns the
current command line arguments as an array.
Example:
Following example illustrates how we can print “Hello Scala”
with out main method.
Save the file as − HellowWorld.scala.
HelloWorld.scala //File name
package runnerdev
object HelloWorld extends App {
println("Hello Scala")
}
compile
and run the above example as follows
scala>
scalac HelloWorld.scala
scala>
scala HelloWorld
Output:
Hello
Scala