Java Predicate in java.util.function


#1

I ran into a piece of Java interface code like:

public Instance getX(Predicate<? super E> ret);

If I want to write this inside a Scala trait and leave it undefined for now of course, what is an equivalent for Predicate and how will the type parameter <? super E> look like in Scala?


#2

I believe it will look something like:

trait Trait[E] {
  def getX[E1 >: E](ret: E1 => Boolean): Instance
}

As per the Predicate documentation, ‘This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.’ Scala 2.12 onwards supports Java 8 functional interfaces seamlessly and so we can just use a Scala function type in place of the specialized Java type.

Java’s <? super E> means 'any type that is a supertype of E', this can mean E itself. In Scala we can describe that with the >: type bound.


#3

Ah, I see…Functional Interface supports Java 8 functional interfaces…
But we can replace that with a Scala function type, right.,.as you suggest.
And that’s why you place the Java ‘function’ getX(Predicate<? super E> ret) is placed inside a trait.

Thank you so much. I will try it out now…


#4

So, in Scala, >: (the type bound) is to be interpreted as “any type that is a supertype of E”…

I am a little confused by that E1.


#5

You wouldn’t use the type bound in Scala because function parameters are already contravariant. Java only needs ? super X and ? extends X everywhere because it doesn’t have declaration-site variance.


#6

Ah, ha…that term came up again today. I need to read up on that.