Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics: Functional-like max()

Tags:

java

generics

Function abstraction:

  public abstract class Function<X, Y> {     
      abstract Y apply(X x);      
  }

max method implementation

public static <V extends Comparable<V>> Function<List<V>, V> max() {

    return new Function<List<V>, V>() {
        @Override
        public V apply(List<V> list) {
            return Collections.max(list);
        }
    };
}

And usage (how it should look like)

Date result = max().apply(datesList);

But I get this error and don't understand why it requires Object

incompatible types; inferred type argument(s) java.lang.Object do not conform to bounds of type variable(s) V
found   : <V>project.Function<java.util.List<V>,V>
required: java.lang.Object

I have read big amount of similar QA but didn't get how to fix this. Thanks.

like image 325
Igor Konoplyanko Avatar asked Mar 21 '12 13:03

Igor Konoplyanko


People also ask

What is the difference between generic types and functions in Java?

There are some fundamental differences between the two approaches to generic types. Generic Method: Generic Java method takes a parameter and returns some value after performing a task. It is exactly like a normal function, however, a generic method has type parameters that are cited by actual type.

How to find the maximum value from a given type in Java?

To write a java program to find the maximum value from the given type of elements using a generic function. Create a class Myclass to implement generic class and generic methods. Get the set of the values belonging to specific data type. Create the objects of the class to hold integer,character and double values.

What is a generic method in Java?

Generic Method: Generic Java method takes a parameter and returns some value after performing a task. It is exactly like a normal function, however, a generic method has type parameters that are cited by actual type.

What are the common type parameters of generic class in Java?

The common type parameters are as follows: Like the generic class, we can create a generic method that can accept any type of arguments. Here, the scope of arguments is limited to the method where it is declared. It allows static as well as non-static methods. Let's see a simple example of java generic method to print array elements.


1 Answers

Java has a very limited type inference. If you write this:

Date result = max().apply(datesList);

it is not sophisticated enough to infer the type parameter of the max() method, V, so it takes java.lang.Object instead. You could try this:

Function<List<Date>, Date> fn = max();
Date result = fn.apply(dates);

Or, if you want to write it in one line, you could do the following, assuming that your max() method is defined in a class named Example:

Date result = Example.<Date>max().apply(dates);
like image 151
Jesper Avatar answered Oct 22 '22 08:10

Jesper