This draft deletes the entire topic.
Examples
-
object HelloWorld extends App { println("Hello, world!") }
By extending the
App
trait, you can avoid defining an explicitmain
method. The entire body of theHelloWorld
object is treated as "the main method".2.11.0Delayed Initialization
Per the official documentation,
App
makes use of a feature called Delayed Initialization. This means that the object fields are initialized after the main method is called.2.11.0Delayed Initialization
Per the official documentation,
App
makes use of a feature called Delayed Initialization. This means that the object fields are initialized after the main method is called.DelayedInit
is now deprecated for general use, but is still supported forApp
as a special case. Support will continue until a replacement feature is decided upon and implemented.To access command-line arguments when extending
App
, usethis.args
:object HelloWorld extends App { println("Hello World!") for { arg <- this.args } println(s"Arg=$arg") }
When using
App
you need not override themain
method: simply use the body of the class as themain
method. -
Place this code in a file named
HelloWorld.scala
:object Hello { def main(args: Array[String]): Unit = { println("Hello World!") } }
To compile it to bytecode that is executable by the JVM:
$ scalac HelloWorld.scala
To run it:
$ scala Hello
When the Scala runtime loads the program, it looks for an object named
HelloWorld
with amain
method. Themain
method is the program entry point and is executed.Note that, unlike Java, Scala has no requirement of naming objects or classes after the file they're in. Instead, the parameter
Hello
passed in the commandscala Hello
refers to the object to look for that contains themain
method to be executed. It is perfectly possible to have multiple objects with main methods in the same.scala
file.The
args
array will contain the command-line arguments given to the program, if any. For instance, we can modify the program like this:object HelloWorld { def main(args: Array[String]): Unit = { println("Hello World!") for { arg <- args } println(s"Arg=$arg") } }
And then execute it:
$ scalac HelloWorld.scala $ scala HelloWorld 1 2 3 Hello World! Arg=1 Arg=2 Arg=3
-
-
Scala can be used as a scripting language. To demonstrate, create
HelloWorld.scala
with the following content:println("Hello")
Execute it with the command-line interpreter (the
$
is the command line prompt):$ scala HelloWorld.scala Hello
If you omit
.scala
(such as if you simply typedscala HelloWorld
) the runner will look for a compiled.class
file with bytecode instead of compiling and then executing the script.Note: If scala is used as a scripting language no package can be defined.
In operating systems utilizing
bash
or similar shell terminals, Scala scripts can be executed using a 'shell preamble'. Create a file namedHelloWorld.sh
and place the following as it's contents:#!/bin/sh exec scala "$0" "$@" !# println("Hello")
The parts between
#!
and!#
is the 'shell preamble', and is interpreted as a bash script. The rest is Scala.Once you have saved the above file, you must grant it 'executable' permissions. In the shell you can do this:
$ chmod a+x HelloWorld.sh
(Note that this gives permission to everyone: read about chmod to learn how to set it for more specific sets of users.)
Now you can execute the script like this:
$ ./HelloWorld.sh
-
Description Code Assign immutable int value val x = 3
Assign mutable int value var x = 3
Assign immutable value with explicit type val x:Int = 27
Assign lazily evaluated value lazy val y = print("Sleeping in.")
Bind a function to a name val x = (x: Int) => x * x
Bind a function to a name with explicit type val x:Int => Int = (x: Int) => x * x
Define a method def f(x)= x * x
Define a method with explicit typing def f(x: Int): Int = x * x
Define a class class Hopper(someParam: Int) { ... }
Define an object object Hopper(someParam: Int) { ... }
Define a trait trait Grace { ... }
Get first element of sequence Seq(1,2,3).head
If switch val result = if(x > 0) "Positive!"
Get get all elements of sequence except first Seq(1,2,3).tail
Loop through a list for { x <- Seq(1,2,3) } print(x)
Nested Looping for {
x <- Seq(1,2,3)
y <- Seq(4,5,6)
} print(x + ":" + y)For each list element execute function List(1,2,3).foreach { println }
Print to standard out print("Ada Lovelace")
Sort a list alphanumerically List('b','c','a').sorted
-
When you execute
scala
in a terminal without additional parameters it opens up a REPL (Read-Eval-Print Loop) interpreter:nford:~ $ scala Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_66). Type in expressions for evaluation. Or try :help. scala>
The REPL allows you to execute Scala in a worksheet fashion: the execution context is preserved and you can manually try out commands without having to build a whole program. For instance, by typing
val poem = "As halcyons we shall be"
would look like this:scala> val poem = "As halcyons we shall be" poem: String = As halcyons we shall be
Now we can print our
val
:scala> print(poem) As halcyons we shall be
Note that
val
is immutable and cannot be overwritten:scala> poem = "Brooding on the open sea" <console>:12: error: reassignment to val poem = "Brooding on the open sea"
But in the REPL you can redefine a
val
(which would cause an error in a normal Scala program, if it was done in the same scope):scala> val poem = "Brooding on the open sea" poem: String = Brooding on the open sea
For the remainder of your REPL session this newly defined variable will shadow the previously defined variable. REPLs are useful for quickly seeing how objects or other code works. All of Scala's features are available: you can define functions, classes, methods, etc.
Remarks
Most given examples require a working Scala installation. This is the Scala installation page, and this is the 'How to setup Scala' example. scalafiddle.net is a good resource for executing small code examples over the web.
Topic Outline
- Hello World by extending App
- Hello World by Defining a 'main' Method
- Hello World as a script
- Scala Quicksheet
- Using the Scala REPL
Versions
Sign up or log in
Save edit as a guest
Join Stack Overflow
Using Google
Using Facebook
Using Email and Password
We recognize you from another Stack Exchange Network site!
Join and Save Draft