Last active
August 22, 2019 20:19
-
-
Save calaveraInfo/207cf0775d3e8926dcb5bc934f72af41 to your computer and use it in GitHub Desktop.
Generic polymorphic function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package cz.cez.trading.algo.core; | |
import static org.junit.jupiter.api.Assertions.assertEquals; | |
import org.junit.jupiter.api.Test; | |
public class GenericPolymorphicFunctionTest { | |
@Test | |
public void testPolymorphicFunction() { | |
assertEquals(4, square(new ContainerOfInt(2))); | |
} | |
// how to write signature of this function? | |
// function is fully polymorhic, ie it doesn't care about the generic type of it's parameter at all | |
// raw types are discouraged: | |
// private static int square(ContainerOfSomething param) { | |
// is this correct and approved by Sonar?: | |
private static int square(ContainerOfSomething<?> param) { | |
return param.getSomeNumberDerivedFromContent()*param.getSomeNumberDerivedFromContent(); | |
} | |
public interface ContainerOfSomething<T> { | |
int getSomeNumberDerivedFromContent(); | |
T getContent(); | |
} | |
public class ContainerOfInt implements ContainerOfSomething<Integer> { | |
private Integer content; | |
public ContainerOfInt(Integer content) { | |
this.content = content; | |
} | |
@Override | |
public int getSomeNumberDerivedFromContent() { | |
return content; | |
} | |
@Override | |
public Integer getContent() { | |
return content; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Scratch { | |
public static void main(String[] args) { | |
List raw = new ArrayList<>(); | |
raw.add(new Animal()); | |
List<?> generic = new ArrayList<>(); | |
generic.add(new Animal()); | |
} | |
static class Animal { | |
} | |
static class Dog extends Animal { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment