mkIf vs if / then

The implicit else branch of lib.mkIf is the least important difference between that and if-then-else construct. You could achieve the same with lib.optionalAttrs, which has the same interface:

Rather, the main difference is that mkIf produces an attribute set that is handled specially by the NixOS module system and keeps the contents available:

This will allow the module system to remain aware of the contents even when the condition is false and it can validate them.

That is also one of the reasons mkIf is preferred in NixOS modules. The other is that evaluation of the condition can be more lazy.

Just note that mkIf produces a special attribute set so the result will need to be merged with lib.mkMerge – you can no longer just use standard Nix operators:

config = {
  environment.systemPackages = [
    pkgs.ripgrep
  # ⬐ THIS IS WRONG!
  ] ++ mkIf config.my.custom.opt.installvim [
    pkgs.vim
  ];
}
12 Likes