How to declare parametric with return type of a function?

I have a method and I want to declare it with parametric and with return type.
What is the syntax?

f(a::T)::Bool where {T <: Number} = a == 1

The error message is:

ERROR: UndefVarError: T not defined
 [1] top-level scope at REPL[4]:1

I know that there is another way to resolve this problem, but it’s a simplified version of my real problem. It is: I have a method declared with a return type and now I want to put a parametric argument.

The real question is: there is a syntax to declare both parametric argument and return type?


It’s just a slightly annoying parsing issue. Your definition is getting parsed as f(a::T)::(Bool where {T <: Number}), which isn’t what you want. You can do:

julia> (f(a::T)::Bool) where {T <: Number} = a == 1
f (generic function with 1 method)

julia> f(1.0)

And by the way, you can see for yourself how the expression is parsed by quoting it, in case you’re ever curious:

julia> :(f(a::T)::Bool where {T <: Number} = a == 1)
:(f(a::T)::(Bool where T <: Number) = begin
          #= REPL[3]:1 =#
          a == 1

note how the (Bool where T <: Number) is grouped together.


Alternatively, you might find that the long-form function syntax is more readable here (and doesn’t have this parsing issue):

julia> function f(a::T)::Bool where {T <: Number}
         a == 1
f (generic function with 1 method)

julia> f(1)

It’s it. Thanks.

1 Like