Last active
September 16, 2018 14:46
-
-
Save vladris/843e20b4de148a4815686aec50547976 to your computer and use it in GitHub Desktop.
Overloading methods with generic arguments
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
// Since generics in Java are removed at compile-time, we cannot overload methods | |
// based on generic types | |
// Below class does not compile: | |
// Erasure of method Foo(T1) is the same as another method in type Test<T1,T2> | |
// Erasure of method Foo(T2) is the same as another method in type Test<T1,T2> | |
class Generic<T1, T2> { | |
void Foo(T1 arg) { | |
} | |
void Foo(T2 arg) { | |
} | |
} | |
// Using dummy type guards, we can enable overloading | |
// Dummy types, just need to be different | |
class TypeGuard1 { } | |
class TypeGuard2 { } | |
// Compiles, guard argument doesn't have to be provided (unless T1 and T2 are | |
// the same) | |
class GenericWithGuards<T1, T2> { | |
void Foo(T1 arg, TypeGuard1...guard) { | |
} | |
void Foo(T2 arg, TypeGuard2...guard) { | |
} | |
static void Demo() { | |
GenericWithGuards<String, Integer> g = new GenericWithGuards<>(); | |
// The right function gets called depending on argument type | |
g.Foo("Hello"); | |
g.Foo(42); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment