Created by Joshua Nelson with reveal.js
public static String pop(ArrayList<String> list) {
if (list.size() == 0) {
return null;
} else {
return list.remove(list.size() - 1);
}
}
public static <T> T pop_generic(ArrayList<T> list) {
if (list.size() == 0) {
return null;
} else {
return list.remove(list.size() - 1);
}
}
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<int> list = new ArrayList<>();
}
}
non-pointer-generics.java:5: error: unexpected type
ArrayList<int> list = new ArrayList<>();
^
required: reference
found: int
1 error
You can write and compile a .class file that works for types you don't know about yet.
.rlib
s in Rustdef pop(list):
list.pop()
public double add(Object t) throws ReflectiveOperationException {
return new 1.0 + (double) t.getClass().getMethod("doubleValue").invoke(t));
}
pub fn add<T>(a: T, b: T) -> T {
a + b
}
public static int length(CharSequence seq) {
return seq.length();
}
func MyAbs(a Abser) float64 {
return a.Abs()
}
'This function takes a specific type that implements an interface'
Rust example (More info)
pub fn add<T: std::ops::Add<Output = T>>(a: T, b: T) -> T {
a + b
}
Haskell example (More info)
add :: (Num a) => a -> a -> a
add a b = a + b
This works exactly when T has operator +
template<typename T> auto add(T a, T b) -> decltype(a + b) {
return a + b;
}
// This version works only with strings
void add(const char *a, const char *b) {
return;
}