Why is dispatching on `Val` freezing Julia?

I expected a MethodError but this freezes Julia.

f(::Val{0}) = nothing; f(x) = f(Val(x)); f(1)
julia> versioninfo()
Julia Version 1.10.3
Commit 0b4590a5507 (2024-04-30 10:59 UTC)
Build Info:
  Official https://julialang.org/ release
Platform Info:
  OS: macOS (arm64-apple-darwin22.4.0)
  CPU: 8 × Apple M1
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-15.0.7 (ORCJIT, apple-m1)
Threads: 1 default, 0 interactive, 1 GC (on 4 virtual cores)
Environment:
  JULIA_EDITOR = code
  JULIA_NUM_THREADS = 

You get an infinite recursion. Val(1) creates the object Val{1}(), which then dispatches to your fallback method again, wrapping it in another Val (resulting in Val{Val{1}()}()) and so on. Nothing ever unwraps the Val & decreases x, so your ::Val{0} method is never hit.

3 Likes

Got it. I think I’d done something similar before and someone in the forum had helped me figure out what was going on. It’ll take me a few tries.