Skip to content

Instantly share code, notes, and snippets.

@elskwid
Forked from penryu/ex.scala
Created October 6, 2015 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elskwid/74f97ee86db4b4fb979f to your computer and use it in GitHub Desktop.
Save elskwid/74f97ee86db4b4fb979f to your computer and use it in GitHub Desktop.
object Example {
def main(args: Array[String]): Unit = {
println("Scala!")
// create some values to use
// TERM: assignment
val a = 1
val b = 2
val c = 3
val d = 4
val e = 5
// total the numbers
// TERM: operation, operators, expression
val total = a + b + c + d + e
// variable to indicate if we should print the total
val should_print_total = true
// output the total (if the variable is set)
// TERM: interpolation, conditional, boolean, control flow
if (should_print_total) {
println(s"The total is $total")
}
// output the total if it is equal to
if (total == 15) {
println("The total was 15 just like we wanted")
}
// create a list of numbers
// TERM: list
val list = List(a, b, c, d, e)
// how many numbers do we have?
// TERM: method, interpolation
println(s"There are ${list.size} numbers in the list")
// output each number
// TERM: iteration, interpolation, view, zip, match
list.view.zipWithIndex.foreach {
case (number: Int, index: Int) =>
println(s"The number $number is at index $index in the list")
}
// are the numbers even or odd?
// TERM: function, map
def is_even(n: Int): Boolean = (n % 2) == 0
list.map { (n: Int) =>
if (is_even(n)) s"$n is even" else s"$n is odd"
}.foreach(println)
// is there a quicker way to get the total? in this language?
// TERM: fold, method, interpolation
println(s"The total is ${list.fold(0)(_ + _)}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment