Skip to content

Instantly share code, notes, and snippets.

@jehrhardt
Created August 31, 2015 09:32
Show Gist options
  • Save jehrhardt/eff66045f62d32c1b81b to your computer and use it in GitHub Desktop.
Save jehrhardt/eff66045f62d32c1b81b to your computer and use it in GitHub Desktop.

Basics

Basics lesson of the workshop.

First step

println("Hello world")

Basic types

Number literals

true  Boolean
1  Int
1L  Long
1.0  Double
1.0f  Float
'1'  Char
"1"  String

Numbers are objects. All objects inherit from AnyRef.

Operators are functions and functions are operators

1 + 11.+(1)
"Hello world".indexOf("w") ⇔ "Hello world" indexOf "w"

Equality == is equals reference equality by eq.

There are more operators (logical, bitwise, …).

var, val, def

Variables can be change

var i = 1
i = i + 1
i

Values can not be changed

val i = 1
i = i + 1  compile error
i

def and val are executed differently

var i = 1

val j = i + 1
def k = i + 1

j
k

i = i + 1

j
k

lazy can defer val (Scala console)

The type can be declared explicitly or be calculated by the compiler.

val i = 1
val j: Int = 1
val k: Double = 1

Types are also working for def

def i: Int = 1 + 1
val j: Int = i

Functions

Define a simple function.

1  Int
(x: Int) => x + 1  (Int) => Int

Name a function with val or def

val i = (x: Int) => x + 1
i  returns function object
i.apply(1)  executes function
i(1)  short cut
i eq i  true

def j = (x: Int) => x + 1def j: (Int) => Int = (x) => x + 1def j: (Int) => Int = _ + 1
j
j(1)
j eq j  false

def creates a function, that can have parameters

def k(x: Int): Int = x + 1
k  compile error
k(1)

Call by name vs call by value

Call by value is default behavior. Call by name has a short cut.

def i(x: Int): Int = x + 1

def j(x: () => Int): Int = x() + 1
j(() => 1)

def k(x: => Int): Int = x + 1
k(1)

Currying

def i(x: Int)(y: Int) = x + y
i(1)(1)

def j = i(1) _
j(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment