Object Oriented
Functional
var capital = Map("US" -> "Washington", "France" -> "Paris")
capital += ("Japan" -> "Tokyo")
println(capital("France"))
def factorial(x: BigInt): BigInt =
if (x == 0) 1 else x * factorial(x - 1)
// factorial(30) = 265252859812191058636308480000000: BigInt
import java.math.BigInteger
def factorial(x: BigInteger): BigInteger =
if (x == BigInteger.ZERO)
BigInteger.ONE
else
x.multiply(factorial(x.subtract(BigInteger.ONE)))
BigInt, Int, and basic types are wrapped around Java's classes
Every value is an object and every operation is a method call
val x: Int = 3
val y = 3 + 5 // Int + Int
val z = (v: Int) => v + 4 // Functions are Function objects
Functions are first class members
List(1, 2, 3, 4, 5, 6).foreach(println)
def myFunction(f: Int => Int, v: Int) = {
f(v)
}
def insideFunction(x: Int) = {
x * 2
}
myFunction(insideFunction, 8) // 16
Immutability: Operations should map input values into output values
val x = List(1, 2, 3, 4, 5)
val y = x.map( n => n * 2 )
println(x) // List(1, 2, 3, 4, 5)
println(y) // List(2, 4, 6, 8, 10)
Java
// this is Java
class MyClass {
private int index;
private String name;
public MyClass(int index, String name) {
this.index = index;
this.name = name;
}
}
Scala
class MyClass(index: Int, name: String)
Java
boolean nameHasUpperCase = false; // this is Java
for (int i = 0; i < name.length(); ++i) {
if (Character.isUpperCase(name.charAt(i))) {
nameHasUpperCase = true;
break;
}
}
Scala
val nameHasUpperCase = name.exists(_.isUpper)
val list/*: List[Int]*/ = List/*[Int]*/(1, 3, 5, 7, 10)
val x = list.map( (n/*Int*/) => n * 2 )
With Scala
(below)
$ scala
1 // Int
1.444 // Double
true // Boolean
"Hello, Scala!" // String
(1 + 2) * 3
"Hello, Scala!".size
1.to(10) // 1 to 10
Operators are just methods with symbolic names
Text
3 + 2 == 3.+(2)
val radius = 10
val pi = 3.14159
pi * radius * radius
def square(x: Double) = x * x
square(3.0) // = ???
// Multiple parameters
def sumOfSquares(x: Double, y: Double) = square(x) + square(y)
def abs(x: Int) = if (x >= 0) x else -x
// or
def abs2(x: Int) = {
if (x >= 0) {
x
} else {
-x
}
}
Exercise:
https://www.scala-exercises.org/scala_tutorial/functional_loops
val list = List("1", "2", "3", "4") // List[String]
val myMap = Map(
1 -> "one",
2 -> "two",
3 -> "three")
val seq = Seq("1", "2", "3", "4") // Seq[String]
val range = 1 to 5
val list = List(1, 2, 3, 4)
// Map
list.map(x => x * 2) // List(2, 4, 6, 8)
val list = List(1, 2, 3, 4, 5, 6)
// Filter
list.filter(x => x < 4)
def getOdds(l: Int, k: Int): List[Int] = {
??? // All of your code here
}
getOdds(1, 10) // Should be 1, 3, 5, 7, 9
class Dog(val name: String) {
def bark = println("Woof woof")
def call = println("Comming!")
}
val dog = new Dog("Pablito")
case class Person(fullName: String, age: Int)
object Person {
private val king = Person("Tomas", 39)
def recognizeActualKing = king.fullNAme
}