What is 'Val'

What does ‘Val’ mean here:

function num_chunks(::Val{B}) where {B}
    if B ≤ 0
        throw(ArgumentError("`B` must be positive!"))
    elseif B ≤ 8
        return 1, UInt8
    elseif B ≤ 16
        return 1, UInt16
    elseif B ≤ 32
        return 1, UInt32
        return (B - 1) ÷ 64 + 1, UInt64

I got a method error with


Several of your questions can be answered by using the documentation at docs.julialang.org or the ? in the Julia shell. Give that a try. Press ? in the shell, then type the name you have a question about, then press enter. If you still have questions after reading that, please narrow down your question.

1 Like

The problem is that the doc is not necessarily clear for a newbie.

It would be helpful if you could tell us what is not clear.

help?> Val
search: Val values valtype eval evalpoly evalfile @eval isvalid


  Return Val{c}(), which contains no run-time data. Types like this
  can be used to pass the information between functions through the
  value c, which must be an isbits value or a Symbol. The intent of
  this construct is to be able to dispatch on constants directly (at
  compile time) without having to test the value of the constant at
  run time.


  julia> f(::Val{true}) = "Good"
  f (generic function with 1 method)

  julia> f(::Val{false}) = "Bad"
  f (generic function with 2 methods)

  julia> f(Val(true))

You need

julia> num_chunks(Val(9))
(1, UInt16) 

Val is for taking a normal value and making a special type out of it.

Sometimes people use this for a bit of extra performance, but it makes the code somewhat awkward and doesn’t necessarily actually help performance. I think it used to be more helpful for performance in an earlier Julia version than it is now, due to more recent developments in the compiler. It’s possible it might be used unnecessarily here.