Scala (1) The Basics of Scala

1. Hello world:

I suggest to start working with Scala in IntelliJ IDEA which is a integrated development environment (IDE) for Java development.

You can easily setup the Scala development environment on IntelliJ IDEA. See Getting Started with Scala in IntelliJ for more information.

object Main extends App {
    println("Hello world")
}

2. Create a variable:

To define a mutable variable, we use the keyword var with the following syntax:

var name = "Cooper"
name = "Cooper Bear" // set name to a new literal

Note that "name" is a mutable variable which means we can reassign the value to that variable.

Scala is a functional programming language which favors the immutable pattern.

We use val to define the immutable variable:

val name = "Cooper"
name = "Cooper Bear" // raise reassignment error!!

The immutable variable is similar to a constant in C++, which can't be reassigned to the new value.


3. Type Inference

Scala has a built-in type inference mechanism which allows the programmer to omit certain type annotations. However we can explicitly assign the type to the variable.

var name: String = "Cooper"

The above syntax defines a variable called "name" which is a String variable.

println(name.getClass()) // java.lang.String

getClass() is used to get the data type of the variable.

We can see that the String in Scala is a wrapper of java.lang.String.


4. A Taste of Functional Programming:

Scala is a functional programming language which means a function value is an object in Scala.

To explain what is a function value we need to define a function first. The following syntax define a function called "greet" which prints "Hello world" on the stdout.

def greet(): Unit = println("Hello world")
greet()

Then we can pass the function to a variable

val hello:()=>Unit = greet
hello()

The function can also be passed to another function.

val names = List("Ben", "Alice")
names.foreach(println) // iterate through names and print

留言

熱門文章