How can I use my Functional interface to return me a Cat instead of a Kitten?



So, I have 2 classes: Cat and Kitten extends Cat. They have fields (int age, String name) and a constructor. I am trying to create my Functional interface that takes Kitten as input parameter and returns me a Cat (and makes it 2 years elder).

@FunctionalInterface
public interface CatToKittenFunction <Kitten, Cat>{
Cat grow(Kitten k);
}

And Main class

public static void main(String[] args) {
    Cat smallCat = new Kitten(1, "Push");
    Cat oldCat = grow(s -> s.getClass(), (Kitten)smallCat);
    System.out.println("oldCat.getClass() = " + oldCat.getClass());
}

private static Cat grow(CatToKittenFunction function, Kitten kitten){
    return (Cat) function.grow(kitten);
}

I don’t have an idea where I can change its age and I have ClassCastException as well. What am I do wrong?

Answer

  • You can try implementing this by using your functional interface :

  • Below Lambda expression will take Kitten as input and make it’s age 2 year elder

     CatToKittenFunction<Kitten, Cat> fn = (Kitten k) ->{
          return new Cat(k.age+2,k.name);
      };
    
  • Call the grow function by passing kitten object and it will returns the Cat incremented age with 2 year elder.

      Cat oldCat = fn.grow(smallCat);
      System.out.println("oldCat.age: " + oldCat.age);
      System.out.println("smallCat.age: " + smallCat.age);
    


Source: stackoverflow