Skip to content

Inline and Implicit Analysis

This pair of metrics surfaces metaprogramming and API ergonomics signals that are easy to miss in code review.

What it Measures

  • inline (Scala 3):
    • inline def/val/var: definitions with the inline modifier.
    • inline parameters declared as inline p: T.
  • using count (Scala 3).
  • givens (Scala 3):
    • All given instances (given definitions).
    • Given conversions: given Conversion[A, B].
  • @inline methods (Scala 2).
  • implicit conversions: heuristic subset of implicit defs that look like implicit def f(a: A): B (single non- implicit parameter list, non-Unit result). These are the ones that most often surprise readers and JIT (Scala 2).

Why it Helps

  • Visibility into compile-time metaprogramming/optimizations; prevents overuse that may bloat the code or slows down compile.
  • Surfaces API ergonomics; too many context requirements can harm discoverability.

Inline & Implicit Usage: Power with Restraint

inline can erase tiny abstractions in hot paths, and given/implicits enable elegant APIs. Both increase compile‑time cleverness. Use them when they clearly help, document intent, and keep the surface area small.

1. Inline for tiny hot-path helpers

This removes call overhead and enables constant folding in simple cases. Keep inline bodies tiny and pure; larger bodies hurt compile times and readability.

inline def fastAbs(x: Int): Int = if x >= 0 then x else -x

Note

Measure before/after. Keep inline bodies small and side-effect free.

2. Given instances with clear names and scopes

Prefer local/module scopes so the resolution is predictable. Tests can supply alternative givens, and call sites remain explicit with using when needed.

trait Clock { def now(): Instant }
given systemClock: Clock with
  def now(): Instant = Instant.now()

def stamp(msg: String)(using Clock): String =
  s"${summon[Clock].now()}: $msg"
// Given in a very broad package object leaks everywhere
given noisy: Clock = ???

Warning

Prefer local givens or module-level scopes; avoid surprising global instances.

3. Document the magic

Anytime you lean on inline or givens/implicits, write one or two sentences explaining the why. Future maintainers will thank you, and reviewers can assess whether the cleverness is worth it.