Typesafety with Function varargs as parametrs - java

I need to write a class with function like this
class Converter <T>{
public <R> R convertBy(Function<T,?>... args){
Function<T,?> function = args[0];
// doing something
return function.apply(t);
}
}
I need this method to be type safe i.e first Function need from args needs to have the same argument type as this class type. For example, if my Converter would be Converter<String> I need to check (at the compile time) if the first function has String parameter.
Also, when I wrote method like that is saying that it returns object, and I cannot do
int a = converter.convertBy(func1,func2);
because is saying that Object is not convertible to int.
-- Edit
Maybe with bigger picture will be easier to get what is it about. So the meaning of convertBy function is that it can with easy combine diffrent operation on different types.
This is working, when I define function like
public <R> R convertBy(Function... args)
but then It is not type safe. What I need, is to make sure If my Converter is 'Converter ' user cannot pass as first parametr function like
Function func = (string)->{ return (String)string.length();}
Also I cannot change paramters from
convertBy(Function... args)
to
convertBy(Function first, Function... rest)
edit.
Well I what appeared later is that I can do that. But it still doesn't check.
Thank You.

The way to make sure at compile time that your Function has return type R is to declare it as Function<T,R>.
If you also want to accept an unspecified number of other functions with different types, you could write your function like this:
public <R> R convertBy(Function<T,R> first, Function<?,?>... others)
That way the return type matches the return type of the first function.
But without knowing what you're trying to do with those other functions, it is hard to know what types they are supposed to have.

You could make it without varargs quite easily actually, all you need to do is to make several methods with different amount of functions in those. This approach is often used for optimization anyway, as varargs aren't nearly as optimized as normal methods.
<R> R convertBy(Function<T, R> fnc);
<R,U> R convertBy(Function<T, U> fnc1, Function<U, R> fnc2);
// etc.
You can't ensure type safety in an array of Function, that is just impossible task. You lose type information there, and the best you could do would be checking the type using reflections, which happens at runtime, thus type safety is not checked compile time.
So I advise just sticking to the andThen or compose methods unless you have plenty functions and the utility brings you enough syntax sugar to be worth doing it that way.

Related

What is the translation of this Java method signature in plain English?

I'm porting JBox2D to Xojo. Java is not a language I know well but there are enough similarities to Xojo for this to be the easiest way to port Box2D to it.
I am well into the port but I cannot fathom the meaning of this method signature:
public static <T> T[] reallocateBuffer(Class<T> klass, T[] oldBuffer, int oldCapacity,
int newCapacity) {}
Does this method return an array of any class type?
Does Class<T> klass mean that the klass parameter can be of any class?
Basically, that function signature makes it possible to handle arrays of different types in one place. If it were programmed in C, it would probably use a macro (#define) to accomplish something similar.
Syntactically, the <T> means: T is a placeholder for any class of objecs that arr passed to this function. If you pass an object of type T to this function, then all other places that mention T inside this function will also mean that type. That way, you don't have to write separate functions if you want to handle different types. Internally, the compiler may well generate separate code for each type, though. So, generics are a shortcut, letting you work with variable types.
This will be difficult to translate into Xojo, as it doesn't provide any means for that.
Since Xojo does not offer support for Generics (Templates), you need to find out which different array types are actually used with this function, and write a specific function for each of these cases.
You may be able to work with Xojo's base class Object as the parameter, although passing arrays of Object will often not work due to Xojo's rather static type checking on arrays.
A trick around this would be to pack the array into a Variant, and then special handle each array type inside. That would still not be generic but would at least keep it all in a single function, like the original does.
Something like this:
Sub createObjects(arrayContainer as Variant, newAmount as Integer)
if not arrayContainer.IsArray then break ' assertion
// Handle case when array is of MyObject1
try
#pragma BreakOnExceptions off ' prevents Debugger from stopping here
dim a() as MyObject1 = arrayContainer
#pragma BreakOnExceptions default
for i as Integer = 1 to newAmount
a.Append new MyObject1
next
return
catch exc as TypeMismatchException
' fall thru
end try
// Handle more types here
break
End Sub
Then call it like this:
dim d() as MyObject1
createObjects d, 3

Can I do type inference in Java? Yes I can

I am an experienced C++ developer learning Java abstract concepts.
I was looking if I can do type inference in java and the answer is usually no and that I need to pass the Class type when calling a generic function. like so:
<T> void test(T t, Class<T> clazz);
I though this is redundant and that the compiler should be able to infer the type (C++ does it why can't Java :p) but then when I understood how generics are implemented under the hood I realized that T is essentially Object at runtime.
But then I realized that I can still call Object member functions on an instance of T. So I'm able to do something like this:
<T> void test(T t) {
if (t.getClass() == Integer.class ) {
// T is of type Integer.
}
}
1- Is there an advantage of either techniques over the other (i.e. passing Class<T> over checking Class type using getClass)?
2- Is there anything wrong with the second approach? The reason I am asking is that I have seen people go to the extend of using reflection and some obscure techniques before following what I've written above. Ideas?
There are a few issues here:
In general, you shouldn't really be inspecting the types of things at runtime. It's not wrong, per se, but if you feel the need to do it, then you're probably taking the wrong approach. For generics, for example, the whole point of a generic method is that it works regardless of the type argument.
Unlike C++, Java doesn't have any concept of template specialization; and Java programmers are comfortable with this restriction. Idiomatic Java code does not try to circumvent it.
There's no guarantee that t.getClass() is the same as the type T; t could be an instance of a subtype of T, for example. (Whereas a Class<T> is guaranteed to be the type T, unless it's null, or unless the program has "polluted the heap" by circumventing the generic type system.)
If you're going to do this, I'd suggest writing if (t instanceof Integer) instead of doing anything with getClass().
Is there anything wrong in the above approach?
Absolutely! If you have to "unmask" the generic type parameter T to do something special, you might as well do it in a separate piece of code, and either pass it on the side the way the class is passed, or require T implement a specific interface that provides the "special" functionality.
Is there an advantage of either techniques above over the other (i.e. passing Class<T> over checking Class type using getClass)?
Passing Class<T> technique has a specific reason behind it - letting you construct objects when you have none to begin with. In other words, it is applicable when you have no object on which to call getClass(), but you want to return an instance of T instead.

Java generic type comparison

I'd like to know if something like this is possible in Java (mix of C++ and Java ahead)
template<typename T> bool compare(Wrapper wrapper) {
if(wrapper.obj.getClass().equals(T.class))
return true
return false
}
To clarify, the function takes in an object which contains a java.lang.object, but I'd like to be able to pass that wrapper into this generic comparison function to check whether that object is of a particular type, ie
if(compare<String>(myWrapper))
// do x
No, it's not possible due to erasure. Basically, the compare method has no idea what T is. There's only one compare method (as opposed to C++, where there's one per T), and it isn't given any information about how it was invoked (ie, what the caller considered its T to be).
The typical solution is to have the class (or method) accept a Class<T> cls, and then use cls.isInstance:
public <T> boolean compare(Wrapper wrapper, Class<T> cls) {
return cls.isInstance(wrapper.obj);
}
// and then, at the call site:
if (compare(wrapper, Foo.class)) {
...
}
Of course, this means that the call site needs to have the Class<T> object. If that call site is itself a generic method, it needs to get that reference from its caller, and so on. At some point, somebody needs to know what the specific type is, and that somebody passes in Foo.class.
You cannot reference static members of a type parameter (such as you try to do in the form of T.class). You also cannot use them meaningfully in instanceof expressions. More generally, because Java generics are implemented via type erasure, you cannot use type parameters in any way at run time -- all type analysis is performed statically, at compile time.
Depending on exactly what you're after, there are at least two alternative approaches.
The first, and more usual, is to ensure that the necessary types can be checked statically. For example, you might parameterize your Wrapper class with the type of the object it wraps. Then, supposing that you use it in a program that is type-safe, wherever you have a Wrapper<String> you know that the wrapped object is a String.
That doesn't work so well if you want to verify the specific class of the wrapped object, however, when the class to test against is not final. In that case, you can pass a Class object, something like this:
<T> boolean compare(Wrapper<? super T> wrapper, Class<T> clazz) {
return wrapper.obj.getClass().equals(clazz);
}
That checks the class of the wrapped object against the specified class, allowing the method to be invoked only in cases where static analysis allows that it could return true.
You can actually combine those two approaches, if you like, to create a Wrapper class whose instances can hold only members of a specific class, as opposed to any object that is assignable to a given type. I'm not sure why you would want to do that, though.

Why use a wild card capture helper method?

Referring to : Wildcard Capture Helper Methods
It says to create a helper method to capture the wild card.
public void foo(List<?> i) {
fooHelper(i);
}
private <T> void fooHelper(List<T> l) {
l.set(0, l.get(0));
}
Just using this function below alone doesn't produce any compilation errors, and seems to work the same way. What I don't understand is: why wouldn't you just use this and avoid using a helper?
public <T> void foo(List<T> l) {
l.set(0, l.get(0));
}
I thought that this question would really boil down to: what's the difference between wildcard and generics? So, I went to this: difference between wildcard and generics.
It says to use type parameters:
1) If you want to enforce some relationship on the different types of method arguments, you can't do that with wildcards, you have to use type parameters.
But, isn't that exactly what the wildcard with helper function is actually doing? Is it not enforcing a relationship on different types of method arguments with its setting and getting of unknown values?
My question is: If you have to define something that requires a relationship on different types of method args, then why use wildcards in the first place and then use a helper function for it?
It seems like a hacky way to incorporate wildcards.
In this particular case it's because the List.set(int, E) method requires the type to be the same as the type in the list.
If you don't have the helper method, the compiler doesn't know if ? is the same for List<?> and the return from get(int) so you get a compiler error:
The method set(int, capture#1-of ?) in the type List<capture#1-of ?> is not applicable for the arguments (int, capture#2-of ?)
With the helper method, you are telling the compiler, the type is the same, I just don't know what the type is.
So why have the non-helper method?
Generics weren't introduced until Java 5 so there is a lot of code out there that predates generics. A pre-Java 5 List is now a List<?> so if you were trying to compile old code in a generic aware compiler, you would have to add these helper methods if you couldn't change the method signatures.
I agree: Delete the helper method and type the public API. There's no reason not to, and every reason to.
Just to summarise the need for the helper with the wildcard version: Although it's obvious to us as humans, the compiler doesn't know that the unknown type returned from l.get(0) is the same unknown type of the list itself. ie it doesn't factor in that the parameter of the set() call comes from the same list object as the target, so it must be a safe operation. It only notices that the type returned from get() is unknown and the type of the target list is unknown, and two unknowns are not guaranteed to be the same type.
You are correct that we don't have to use the wildcard version.
It comes down to which API looks/feels "better", which is subjective
void foo(List<?> i)
<T> void foo(List<T> i)
I'll say the 1st version is better.
If there are bounds
void foo(List<? extends Number> i)
<T extends Number> void foo(List<T> i)
The 1st version looks even more compact; the type information are all in one place.
At this point of time, the wildcard version is the idiomatic way, and it's more familiar to programmers.
There are a lot of wildcards in JDK method definitions, particularly after java8's introduction of lambda/Stream. They are very ugly, admittedly, because we don't have variance types. But think how much uglier it'll be if we expand all wildcards to type vars.
The Java 14 Language Specification, Section 5.1.10 (PDF) devotes some paragraphs to why one would prefer providing the wildcard method publicly, while using the generic method privately. Specifically, they say (of the public generic method):
This is undesirable, as it exposes implementation information to the caller.
What do they mean by this? What exactly is getting exposed in one and not the other?
Did you know you can pass type parameters directly to a method? If you have a static method <T> Foo<T> create() on a Foo class -- yes, this has been most useful to me for static factory methods -- then you can invoke it as Foo.<String>create(). You normally don't need -- or want -- to do this, since Java can sometimes infer those types from any provided arguments. But the fact remains that you can provide those types explicitly.
So the generic <T> void foo(List<T> i) really takes two parameters at the language level: the element type of the list, and the list itself. We've modified the method contract just to save ourselves some time on the implementation side!
It's easy to think that <?> is just shorthand for the more explicit generic syntax, but I think Java's notation actually obscures what's really going on here. Let's translate into the language of type theory for a moment:
/* Java *//* Type theory */
List<?> ~~ ∃T. List<T>
void foo(List<?> l) ~~ (∃T. List<T>) -> ()
<T> void foo(List<T> l) ~~ ∀T.(List<T> -> ()
A type like List<?> is called an existential type. The ? means that there is some type that goes there, but we don't know what it is. On the type theory side, ∃T. means "there exists some T", which is essentially what I said in the previous sentence -- we've just given that type a name, even though we still don't know what it is.
In type theory, functions have type A -> B, where A is the input type and B is the return type. (We write void as () for silly reasons.) Notice that on the second line, our input type is the same existential list we've been discussing.
Something strange happens on the third line! On the Java side, it looks like we've simply named the wildcard (which isn't a bad intuition for it). On the type theory side we've said something _superficially very similar to the previous line: for any type of the caller's choice, we will accept a list of that type. (∀T. is, indeed, read as "for all T".) But the scope of T is now totally different -- the brackets have moved to include the output type! That's critical: we couldn't write something like <T> List<T> reverse(List<T> l) without that wider scope.
But if we don't need that wider scope to describe the function's contract, then reducing the scope of our variables (yes, even type-level variables) makes it easier to reason about those variables. The existential form of the method makes it abundantly clear to the caller that the relevance of the list's element type extends no further than the list itself.

What's the Java equivalent to C++'s for_each template?

In the following code you're able to apply any Function f (e.g., add, subtract, etc.). How do I do that through Java?
template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f)
{
for ( ; first!=last; ++first ) f(*first);
return f;
}
There are two major changes you'll need to make to this code to make it work in Java. First, you'll need to replace the STL-style iterators with Java-style iterators, which fortunately isn't too hard. Second, you'll have to change the use of a function pointer or functor parameter with an object of a different type, since Java does not support function pointers.
In Java, iterators are heavier than in C++ and encapsulate the full range they traverse, not just the start or end of that range. With a Java iterator, you use the .next() and .hasNext() methods to walk across the range.
As for the function parameter, you will probably need to create your own interface representing some object that can be called as a function. For example:
public interface Operation<T> {
void apply(T argument);
}
This interface is a generic parameterized on some type T saying what the argument type is, and then exports a function called apply() that applies the function.
Given this, a simple but naive way to replicate for_each would be to write
public static <T> forEach(Iterator<T> itr, Operation<T> op) {
while (itr.hasNext())
op.apply(itr.next());
}
The reason I say that this is naive is that it doesn't use bounded wildcards correctly to expand the scope of where it can be used. A more proper version that's more Java-friendly would be this:
public static <T> forEach(Iterator<T> itr, Operation<? super T> op) {
while (itr.hasNext())
op.apply(itr.next());
}
Consult a reference on Java genetics for why this works.
Hope this helps!
To implement the template class you'd use Java Generics
For the callback, more than likely you'd want to create an Interface and pass an object that implemented it to the Generic class where you'd call the method defined therin.
You should use interfaces, but if you want to do it in the hard way, using reflection (not tested, not exception-checked, etc. But you can get the idea):
public void myFunction(Collection items, String methodName) {
foreach(Object o : items) {
Method method = o.getClass().getMethod(methodName);
method.invoke(o);
}
}
With good OO design, first through last would be objects of a specific (implements an interface) type and f() would take an object of that type (interface) as a parameter so you are done--it's pretty much like you wrote.
if you are talking about doing it on primitives instead then it's going to need generics, but at this point you'd want to look for a better design or better way to do that.
You didn't really give enough info for a more detailed answer, if we knew more about the problem you were trying to solve and the restrictions we might be able to give better advice.

Categories