1

I don't know if the title is understandable but I have this:

 public class Product { public Integer getId() {...} public String getName() {...} } public <T,V> static void method(Function<T, V> f, V value) {...} 

and I want to become a compile error when:

 method(Product::getId, "some String"); // id is not String method(Product::getName, 123); // name is not Integer 

But the compiler interpret V as:

java Serializable & Comparable<? extends Serializable & Comparable<?>> 

It compiles but depending on how "method" is implemented, you get an Exception at runtime or it just works wrongly.

How can I instruct the compiler to match the wanted data type? and I don't want to write a "method" for every possible V type.

Thanks!

2
  • Does this answer your question? Commented Feb 26, 2021 at 9:36
  • @AndrewVershinin not really, because they suggest to implement the method like Object.equals but it happens at runtime and I want it at compiling time. But thanks! Commented Mar 1, 2021 at 7:20

1 Answer 1

1

You can enforce the generics by splitting them up accross two method calls, for that you'd need a new class:

public class Value<T, V> { private final Function<T, V> f; public Value(Function<T, V> f) { this.f= f; } public void with(V value) { // move your code from method() into here } } 

And then change method() to something like this:

public static <T, V> Value<T, V> method(Function<T, V> f) { return new Value<>(f); } 

Then you can use it like this:

method(Product::getId).with("123"); // compiler error method(Product::getName).with(123); // compiler error method(Product::getId).with(123); // no error method(Product::getName).with("123"); // no error 
Sign up to request clarification or add additional context in comments.

1 Comment

An extra class and an extra method callback but it does the trick. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.