Tin

Examples · learn/10-generics · 168 of 339

why

Without generics you'd write the same function once per type.

examples/learn/10-generics/why.tintin run examples/learn/10-generics/why.tin
// Without generics you'd write the same function once per type:
fn firstInt(xs: int[]): Option<int> => if xs.len == 0 { None } else { Some(xs[0]) }
fn firstString(xs: string[]): Option<string> => if xs.len == 0 { None } else { Some(xs[0]) }

// With a type parameter T, one function works for any element type.
fn firstOf<T>(xs: T[]): Option<T> => if xs.len == 0 { None } else { Some(xs[0]) }

fn main() {
  print(firstInt([1, 2]))
  print(firstString(["a"]))
  print(firstOf([1, 2]))         // T is int here
  print(firstOf(["a"]))          // and string here
  print(firstOf([true, false]))
}