mirror of
https://github.com/chubin/cheat.sheets
synced 2024-11-11 01:10:31 +00:00
55 lines
1.1 KiB
Plaintext
55 lines
1.1 KiB
Plaintext
// conditional
|
|
if (check) happy else sad
|
|
|
|
// conditional sugar
|
|
if (check) happy // same as
|
|
if (check) happy else ()
|
|
|
|
// while loop
|
|
while (x < 5) { println(x); x += 1}
|
|
|
|
// do while loop.
|
|
do { println(x); x += 1} while (x < 5)
|
|
|
|
// break
|
|
// slides: https://www.slideshare.net/Odersky/fosdem-2009-1013261/21
|
|
import scala.util.control.Breaks._
|
|
breakable {
|
|
for (x <- xs) {
|
|
if (Math.random < 0.1) break
|
|
}
|
|
}
|
|
|
|
// for comprehension: filter/map
|
|
for (x <- xs if x%2 == 0) yield x*10
|
|
// same as
|
|
xs.filter(_%2 == 0).map(_*10)
|
|
|
|
// for comprehension: destructuring bind
|
|
for ((x,y) <- xs zip ys) yield x*y
|
|
// same as
|
|
(xs zip ys) map { case (x,y) => x*y }
|
|
|
|
// for comprehension: cross product
|
|
for (x <- xs; y <- ys) yield x*y
|
|
// same as
|
|
xs flatMap {x => ys map {y => x*y}}
|
|
|
|
// for comprehension: imperative-ish sprintf-style
|
|
// http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax
|
|
for (x <- xs; y <- ys) {
|
|
println("%d/%d = %.1f".format(x, y, x/y.toFloat))
|
|
}
|
|
|
|
// for comprehension: iterate including the upper bound
|
|
for (i <- 1 to 5) {
|
|
println(i)
|
|
}
|
|
|
|
// for comprehension: iterate omitting the upper bound
|
|
for (i <- 1 until 5) {
|
|
println(i)
|
|
}
|
|
|
|
|