Skip to content

Instantly share code, notes, and snippets.

@timohirt
Created October 8, 2013 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save timohirt/6892571 to your computer and use it in GitHub Desktop.
Save timohirt/6892571 to your computer and use it in GitHub Desktop.
case class Score(p1: Int, p2: Int)
// Alles ist eine Expression
val score = Score(5, 1)
val winner = if (score.p1 > score.p2) "Player 1" else "Player 2"
val looser = if (score.p1 > score.p2) "Player 2" else "Player 1"
// Tupel
val winnerLooser =
if (score.p1 > score.p2) ("Player 1", "Player 2")
else ("Player 2", "Player 1")
// Tupel Zugriff
s"Gewinner: ${winnerLooser._1}; Verlierer: ${winnerLooser._2}"
// Funktionen
def lessThan(max: Int, value: Int) = value < max
// Partial applied functions
val lessThan5 = lessThan(max = 5, _: Int)
val lessThan10 = lessThan(max = 10, _: Int)
val numbers: List[Int] = List(1, 2, 3, 6, 8, 34, 17, 42, 54, 100, 117, 1337)
numbers.filter(lessThan5)
numbers.filter(lessThan10)
// functional composition
def double(x: Int) = x * 2
def plusTwo(x: Int) = x + 2
val doubleAndPlusTwo = double _ andThen plusTwo _
val result = doubleAndPlusTwo(5)
// Ranges
val oneToFive = 1 to 5
for (i <- 1 to 5) {
println(i)
}
for (i <- 1 to 5; if i % 2 == 0) {
println(i)
}
// For comprehension
for {
i <- 1 to 5
if i % 2 == 0
} yield i
val players = List("Timo", "Jan", "Lothar", "Sven", "Danny")
val playerPairs = for {
p1 <- players
p2 <- players
if p1 != p2
} yield (p1, p2)
// lazy Evaluation
lazy val lazyPlayerPairs = for {
p1 <- players
p2 <- players
if p1 != p2
} yield (p1, p2)
println(lazyPlayerPairs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment