Last active
February 24, 2016 18:12
-
-
Save camilosampedro/759c5b898a021210be6f to your computer and use it in GitHub Desktop.
Scala simple examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Returns value given the case. If it does not have an else statement, it will always return Unit () | |
val filename = | |
if (!args.isEmpty) | |
args(0) | |
else | |
"default.txt" | |
// Always returns Unit() | |
while (a != 0) { | |
val temp = a | |
a = b % a | |
b = temp | |
} | |
// Always returns Unit() | |
var line = "" | |
do { | |
line = readLine | |
println("Read: " + line) | |
} while (!line.isEmpty) | |
// Always returns Unit() | |
val filesHere = (new java.io.File(".")).listFiles | |
for (file <- filesHere) | |
println(file) | |
for (i <- 1 to 5) | |
println("Iteration " + i) | |
// Filtering a for | |
for (file <- filesHere; if file.getName.endsWith(".scala")) | |
println(file) | |
// Without semicolons | |
for { | |
file <- filesHere | |
if file.isFile | |
if file.getName.endsWith(".scala") | |
} println(file) | |
// Nested for | |
def grep(pattern: String) = | |
for { | |
file <- filesHere | |
if file.getName.endsWith(".scala") | |
line <- fileLines(file) | |
trimmed = line.trim | |
if trimmed.matches(pattern) | |
} println(file + ": " + trimmed) | |
grep(".*gcd.*") | |
val url = | |
try { | |
new URL(path) | |
} | |
catch { | |
case e: MalformedURLException => | |
new URL("http://www.scala-lang.org") | |
} | |
finally { | |
} | |
// Match | |
val firstArg = if (args.length > 0) args(0) else "" | |
firstArg match { | |
case "salt" => println("pepper") | |
case "chips" => println("salsa") | |
case "eggs" => println("bacon") | |
case _ => println("huh?") | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object FileMatcher { | |
private def filesHere = (new java.io.File(".")).listFiles | |
private def filesMatching(matcher: String => Boolean) = | |
for (file <- filesHere; if matcher(file.getName)) | |
yield file | |
def filesEnding(query: String) = | |
filesMatching(_.endsWith(query)) | |
def filesContaining(query: String) = | |
filesMatching(_.contains(query)) | |
def filesRegex(query: String) = | |
filesMatching(_.matches(query)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Taken from Programming in Scala by Martin Odersky, Lex Spoon and Bill Venners