Skip to content

Instantly share code, notes, and snippets.

@camilosampedro
Last active February 24, 2016 18:12
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 camilosampedro/759c5b898a021210be6f to your computer and use it in GitHub Desktop.
Save camilosampedro/759c5b898a021210be6f to your computer and use it in GitHub Desktop.
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
Copy link
Author

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