Skip to content

Instantly share code, notes, and snippets.

@ml10
Forked from jmccance/collection_init.java
Last active January 27, 2016 17:43
Show Gist options
  • Save ml10/d33723b1dbc87c410544 to your computer and use it in GitHub Desktop.
Save ml10/d33723b1dbc87c410544 to your computer and use it in GitHub Desktop.
Overcoming Immutability in Scala
final List<String> fullNames = new ArrayList<>();
for (Name name : names) {
fullNames.add(String.format("%s %s", name.getFirst(), name.getLast()));
}
val fullNames = names.map { name =>
s"${name.first} ${name.last}"
}
val fullNames = names
.filter(name => name.last.startsWith("M"))
.map(name => s"${name.first} ${name.last}")
final Foo foo;
if (someTest()) {
foo = someFoo;
} else {
foo = new Foo();
}
val foo =
if (someTest()) {
someFoo
} else {
new Foo
}
val foo1 =
if (someTest()) {
someFoo
} else {
new Foo
println("Using default value for `foo`")
}
val foo2 =
if (someTest()) {
someFoo
}
val foo3 =
if (someTest()) {
someFoo
} else {
throw new Exception("No value for `foo` provided!")
}
// NOTE: Will not compile!
val foo: Foo =
if (someTest()) {
someFoo
} else {
new Foo
// Developer adds println statement for debugging, but type annotation above
// will catch that they changed the type of the expression.
println("Using default value for `foo`")
}
final Foo foo;
if (someFoo != null) {
foo = someFoo;
} else {
foo = new Foo();
}
val foo = maybeFoo.getOrElse(new Foo)
val foo: Foo =
if (maybeFoo.isDefined) {
foo = maybeFoo.get // Option#get is generally a code smell.
} else {
foo = new Foo
}
final Map<Long, User> usersById = new HashMap<>();
for (User user : users) {
usersById.put(user.getId(), user);
}
val usersById = {
val elems = users.map(u =&gt; (u.id, u))
Map(elems: _*) // The _* syntax allows you to pass a sequence as a vararg
}
def apply[A, B](elems: (A, B)*): Map[A, B]
val usersById = users.map(u => (u.id, u)).toMap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment