twitter/util — pull request #63 by jorgeortiz85 (2013-04-23 15:12:11+00:00)
Title: Add withFilter to Future and Try

Since Scala 2.8.x, guards in for-comprehensions will translate to a call to `withFilter` rather than `filter`. If no `withFilter` method is found, `filter` will be used instead but a deprecation warning will be emitted.

The contract for `withFilter`'s semantics are that the predicate be applied lazily. In Scala's standard library's collections, this is accomplished by `withFilter` returning an instance of intermediate class WithFilter, which is not itself a collection but has `map`/`flatMap`/`foreach` methods that apply both the filter predicate and the transformation in the same pass. See: https://github.com/scala/scala/blob/v2.10.1/src/library/scala/collection/TraversableLike.scala#L680

For collections with at most one element (such as Option, Try, or Future), the laziness or non-laziness of `withFilter` shouldn't matter. For example, Option's `withFilter` method does return an instance of a WithFilter class, but that class makes no attempt to make it's `map`/`flatMap`/`foreach` methods apply the predicate lazily: https://github.com/scala/scala/blob/v2.10.1/src/library/scala/Option.scala#L201

The included implementation forwards `withFilter` calls to `filter`. This removes the deprecation warning without changing the semantics of existing code. This is safe because laziness semantics are probably irrelevant to collections of at most one element. Further, the additional allocation of a new WithFilter instance could impact performance.