Skip to content

Instantly share code, notes, and snippets.

@helenwilliamson
Created January 14, 2014 22:56
Show Gist options
  • Save helenwilliamson/8427562 to your computer and use it in GitHub Desktop.
Save helenwilliamson/8427562 to your computer and use it in GitHub Desktop.
Don't forget that .map works on a function. - MutableThings().addStuff will instantiate 1 MutableThings and return the addStuff function for that specific object - t => MutableThings().addStuff(t) returns a function that creates a MutableThings and calls the addStuff function on this new object.
package main.scala
case class MutableThings(var stuff: List[String] = List()) {
println("Creating new MutableThings")
def addStuff(myStuff: String) = {
this.stuff = List(myStuff)
this
}
}
case class ImmutableThings(stuff: List[String] = List()) {
def addStuff(myStuff: String) = copy(stuff = List(myStuff))
}
object ImmutableThingsTester {
def main(args: Array[String]) {
def convert1(stuffToChange: String*) = stuffToChange.map(MutableThings().addStuff)
def convert2(stuffToChange: String*) = stuffToChange.map(t => MutableThings().addStuff(t))
def convert3(stuffToChange: String*) = stuffToChange.map(ImmutableThings().addStuff)
def convert4(stuffToChange: String*) = stuffToChange.map(t => ImmutableThings().addStuff(t))
println("Mutable case class with function:")
println(convert1("1", "2", "3"))
println("\nMutable case class with anonymous function:")
println(convert2("1", "2", "3"))
println("\nImmutable case class with function:")
println(convert3("1", "2", "3"))
println("\nImmutable case class with anonymous function:")
println(convert4("1", "2", "3"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment