# Val type is type unstable?

**URL:** <https://discourse.julialang.org/t/val-type-is-type-unstable/64336>\
**Category:** General Usage\
**Tags:** code\_warntype, type-stability\
**Created:** [July 9, 2021, 9:32am UTC](https://discourse.julialang.org/t/val-type-is-type-unstable/64336 "2021-07-09T09:32:20Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![shamazmazum](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/shamazmazum/32/25200_2.png) [@shamazmazum](https://discourse.julialang.org/u/shamazmazum)\
**Post date:** [July 9, 2021, 9:32am UTC](https://discourse.julialang.org/t/val-type-is-type-unstable/64336/1 "2021-07-09T09:32:21Z")

</div>

Hello, should I be afraid of `::Val{_A} where _A` in this situation?

```julia
f(x, y, ::Val{:x}) = x
f(x, y, ::Val{:y}) = y
f(x, y, s :: Symbol) = f(x, y, Val(s))

```

```julia
@code_warntype f(1,2,:x)

Variables
  #self#::Core.Const(f)
  x::Int64
  y::Int64
  s::Symbol

Body::Int64
1 ─ nothing
│ %2 = Main.Val(s)::Val{_A} where _A
│ %3 = Main.f(x, y, %2)::Int64
└── return %3

```

Does that mean all my code which uses `Val` is type unstable?

---

<div class="post-metadata">

**Author:** ![GunnarFarneback](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gunnarfarneback/32/1827_2.png) [@GunnarFarneback](https://discourse.julialang.org/u/GunnarFarneback)\
**Post date:** [July 9, 2021, 10:20am UTC](https://discourse.julialang.org/t/val-type-is-type-unstable/64336/2 "2021-07-09T10:20:39Z")

</div>

> [@shamazmazum](#):
>
> Does that mean all my code which uses `Val` is type unstable?

Not necessarily. `Val(s)` itself returns different _types_ for different _values_ of `s` and is by definition type unstable. `Val{:x}` on the other hand is a specific type.

In your example the return type of `f` is type stable but the internal type instability would need a (relatively slow) dynamic dispatch to resolve, unless the function is specialized by constant propagation. If you use `Val(:x)`, i.e. with a literal argument, you should see that you get a correctly inferred return type, for example.

Addendum: This is a better illustration of specialization by constant propagation for your example:

```julia
julia> g(x, y) = f(x, y, :x)
g (generic function with 1 method)

julia> @code_warntype g(1, 2)
Variables
  #self#::Core.Const(g)
  x::Int64
  y::Int64

Body::Int64
1 ─ %1 = Main.f(x, y, :x)::Int64
└── return %1

```

---

<div class="post-metadata">

**Author:** ![shamazmazum](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/shamazmazum/32/25200_2.png) [@shamazmazum](https://discourse.julialang.org/u/shamazmazum)\
**Post date:** [July 9, 2021, 10:34am UTC](https://discourse.julialang.org/t/val-type-is-type-unstable/64336/3 "2021-07-09T10:34:06Z")

</div>

Thanks for this answer!
