Skip to content

Instantly share code, notes, and snippets.

@tifletcher
Created February 1, 2018 19:40
Show Gist options
  • Save tifletcher/41c330a69627baf1bcafd5794dd5f194 to your computer and use it in GitHub Desktop.
Save tifletcher/41c330a69627baf1bcafd5794dd5f194 to your computer and use it in GitHub Desktop.
case class Foo (
fooInt: Int,
fooString: String
)
val theFoos = Seq(
Foo(0, "hello"),
Foo(1, "goodbye"),
Foo(2, "")
)
def filterFoos[T](accessor: Foo => T, predicate: T => Boolean) = (f: Foo) => predicate(accessor(f))
// alternately (and exactly the same as the above):
// def filterFoos[T](accessor: Foo => T, predicate: T => Boolean)(f: Foo) = predicate(accessor(f))
val oddFilter = filterFoos[Int](_.fooInt, x => x % 2 != 0)
theFoos.filter(oddFilter)
val stringNonEmpty = filterFoos[String](_.fooString, _.nonEmpty)
theFoos.filter(stringNonEmpty)
@tifletcher
Copy link
Author

tifletcher commented Feb 1, 2018

Er, not "exactly the same"

When using the commented out form of filterFoos you would need to explicitly trigger eta expansion with a trailing _:

val oddFilter = filterFoos[Int](_.fooInt, x => x % 2 != 0) _

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment