Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scala simple examples
// 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?")
}
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))
}
@camilosampedro

This comment has been minimized.

Copy link
Owner Author

@camilosampedro camilosampedro commented Feb 16, 2016

Taken from Programming in Scala by Martin Odersky, Lex Spoon and Bill Venners

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.