1 2 3 | def filter[A](list: List[A], p: A => Boolean):List[A] = { list.filter(p) } |
Ideally, passing in a list of say integers, you would expect the predicate function to not require an explicit type:
1 2 3 | val l = List( 1 , 5 , 9 , 20 , 30 ) filter(l, i => i < 10 ) |
Type inference does not work in this specific instance however, the fix is to specify the type explicitly:
1 | filter(l, (i:Int) => i < 10 ) |
Or a better fix is to use currying, then the type inference works!
1 2 3 4 5 6 7 | def filter[A](list: List[A])(p: A=>Boolean):List[A] = { list.filter(p) } filter(l)(i => i < 10 ) //OR filter(l)(_ < 10 ) |
1 2 3 | public <A> List<A> filter(List<A> list, Predicate<A> condition) { return list.stream().filter(condition).collect(toList()); } |
1 2 3 | List<integer> ints = Arrays.asList( 1 , 5 , 9 , 20 , 30 ); List<integer> lessThan10 = filter(ints, i -> i < 10 ); </integer></integer> |
No comments:
Post a Comment