3 ms·
> I'm not sure why Scala is so obsessed with it, since it's used for so many featurse You might check out http://stackoverflow.com/a/8001065/3614122 http://sta
by ssmoot 12y ago
> I'm not sure why Scala is so obsessed with it, since it's used for so many featurse
You might check out http://stackoverflow.com/a/8001065/3614122 http://stackoverflow.com/a/8001065/3614122. The interesting thing (to me) is that the majority of those are actually the same feature (lifting functions). It's just such a powerful/flexible one that it's often misinterpreted as an entirely new thing in different contexts.
ary.map(_ * 2)
Is no different than:
val f = (_:Int) * 2
ary.map(f)
Or:
val f: Int => Int = _ * 2
ary.map(f)
You're just using type-inference in conjunction with lifting. I wrote a blog post on it that's maybe not complete garbage. ;-) http://www.ssmoot.me/scala-s-magical-placeholder http://www.ssmoot.me/scala-s-magical-placeholder
Some of the other examples of the underscore are pattern-matches, which can be used on the LHS of assignment, similar to Erlang. Which comes in handy writing unit-tests. i.e.: If I expect something to return Some[User], and I'm writing a GET->UPDATE integration test, then I'd probably do something like:
"Update should not blow up" in async {
val Some(user) = await(db.get(userId))
val update = user.copy(name = "bob")
val Success(result) = await(db.put(update))
}
Extractors/Pattern-Matching is way way up there for me. Much more significant than for-comprehensions. Though you could write the same code like:
"Update should not blow up with a for-comprehension" in {
val test = for {
Some(user) <- db.get(userId)
update = user.copy(name = "bob")
Success(result) <- db.put(update)
} yield result
whenReady(result) { "whatever" }
}