Reusing functions that take records as params

I had some joy moment when I realized that I could use different types of records with the same function if I pass an accessor. I thought I had to use objects as hinted in this doc

But then I tried the accessor pattern and it worked like a charm.

Here you can see the example and explanation

2 Likes

Thank you for the article,

You can also use variants for more complex domain models/types which is a bit more typesafe IMO.

1 Like

Variants are awesome, I just haven’t found a way to use Variants outside of another file.
For example if the Variant was declared in Utils.re, how can I use it in Button.re ?

1 Like

In such situation the compiler can not infer the types so you’ve to open the module which has the type annotation to make the type available in scope or annotate expression explicitly.

// Util.re
type t = Foo | Bar;

// Button.re
let a: Util.t = Foo;

let f: Util.t => int =
  x =>
    switch (x) {
    | Foo => 1
    | Bar => 2
    };

// open in module scope
open Util;

let a' = Foo;

let f' = x =>
  switch (x) {
  | Foo => 1
  | Bar => 2
  };

// or open locally (in expression)
let a'' = Util.(Foo);

let f'' = x =>
  Util.(
    switch (x) {
    | Foo => 1
    | Bar => 2
    }
  );


1 Like
2 Likes

ok so I was missing the opening of the file, thanks for the tip! It’s very nice to use Variants. Less of a hazzle

1 Like

Thanks @chenglou
I did see the docs but missed the part of how to use Variants in multiple files. Now I see that I had to open the file with the variant or I can also use it like Variant Needs an Explicit Definition in the docs that @chenglou mentioned

2 Likes