Skip to content

Instantly share code, notes, and snippets.

@cvogt
Last active February 22, 2017 13:51
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 cvogt/65e33ed1f9de93c151e0ff145f8e74fb to your computer and use it in GitHub Desktop.
Save cvogt/65e33ed1f9de93c151e0ff145f8e74fb to your computer and use it in GitHub Desktop.
Scala language proposals for defaults, .copy and overrides
// DEFAULT VALUES
def foo(str: String = "test") = ???
assert( foo.str == "test" ) // new: named access to default values
case class Bar(str: String = "test")
assert( Bar.apply.str == "test" ) // same for case classes via .apply method
// REPETIION-FREE .copy (aka lenses light)
case class Baz(bar: Bar)
val b = Baz( Bar( "world" ) )
assert(
b.copy( bar = b.bar.copy( str = "hello, " ++ b.bar.str ) ) // old: having to repeat repeat b and b.bar
== b.copy( bar _= _.copy( str _= "hello, " ++ _ ) ) // new: short version via ~= operator for modification (alt syntax ~=)
)
// new short version desugars to this (using access to default values):
b.copy( bar = b.copy.bar.copy( str = "hello, " ++ b.copy.bar.copy.str ) )
// MODIFYING OVERRIDES
class Foo{ def str = "world" }
assert(
new Foo{ override str = "hello, " ++ super.str }.str // having to repeat `str` in override
== new Foo{ override str _= "hello, " ++ _ }.str // new: modifying function based on parent value (alt syntax ~=)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment