Java generics: How to encode a Functor interface in Java?

后端 未结 5 705
庸人自扰
庸人自扰 2021-02-01 22:00

I want to define a Functor class in Java. This works:

//a Function
public interface F {
   public R apply(A a);
}

public interface Functor {         


        
5条回答
  •  太阳男子
    2021-02-01 22:29

    I think you want to do something that makes no sense (type wise).

    interface Getter {
     Type get();
    }
    

    If your application wants a getter that returns Integers, don't give it one that returns Objects.

    If you don't know if it will return Objects or Integers you are trying to do something the wrong way.

    If YOU KNOW it will return Integers, then wrap the getter so that it casts to integers.

    Hope this is what you are looking for .

    EDIT: Explanation of why (I think) this can not be done.

    Objects have there types set when you use new. Take each type and replace it with a letter. Take any number of another objects and do the same.

    What letter do you want your function to return? If the answer is that you want a mix, well then its too late. Types are decided at new, and you are already past new.

提交回复
热议问题