Skip to content

Instantly share code, notes, and snippets.

@tdrozdowski
Last active December 27, 2015 08:49
Show Gist options
  • Save tdrozdowski/7299177 to your computer and use it in GitHub Desktop.
Save tdrozdowski/7299177 to your computer and use it in GitHub Desktop.
Part of the Play Framework with Scala in Action session of the Nov 2013 Desert Code Camp. Scala Basics with the REPL. To use these, please install Scala 2.10.x and then use either type in or use the :paste mode of the REPL to copy/pase the following examples.
val foo = "foo"
foo = "Bar"
var bar = "Bar"
foo + bar
val names = List[String]("Foo", "Bar", "Blaz")
names(1)
names.foreach { name => s"Hi, I'm $name!" }
names.mkString(",")
names.map {
name =>
name.getBytes
}
// basic pattern matching
def basic(s : String) = s match {
case "a" => "match!"
case _ => "don't care - try again"
}
def weatherByZip(maybeZip : Option[Int]) = maybeZip match {
case Some(zip) => s"Weather for $zip should be sunny and pleasant!"
case None => s"No zip!"
}
val northPeoriaZip = Some(85383)
val newTownZip = None
weatherByZip(northPeoriaZip)
weatherByZip(newTownZip)
northPeoriaZip.getOrElse("Not provided!")
newTownZip.getOrElse("Not Provided")
def getTemp(zip : Int) = zip match {
case 85383 => Some(72)
case _ => None
}
northPeoriaZip.map { maybeZip => getTemp(maybeZip) }
northPeoriaZip.flatMap(getTemp(_)).getOrElse(-272)
import java.net.URL
import scala.util.{ Try, Success, Failure }
def path(urlString :String) = {
Try(new URL(urlString))
}
path("asdf").getOrElse("Invalid URL!")
path("http://www.desertcodecamp.com/schedule").getOrElse("Invalid URL!")
case class Foo(sum : Int, name : String, time : Option[Long] = None)
var myFoo = Foo(1, "Terry")
myFoo.sum
myFoo.time.getOrElse("0")
//myFoo.sum += 1
val updatedFoo = myFoo.copy(sum = 3, time = Some(1000L))
myFoo.sum
updatedFoo.sum
def printSum(foo: Any) = foo match {
case Foo(1, _, _) => println("I'm #1")
case Foo(sum, _, _) => println(s"sum -> $sum")
case _ => println("not a Foo - wtf?")
}
printSum(myFoo)
printSum(updatedFoo)
printSum(null)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment