How to store the output of typeof expression in a variable?

I have a code snippet like this.

if transitions.is_a? Hash(State, Hash(Token, typeof(transitions.first[1].first[1])))
    return transitions
end

input_consequent_mapping = {} of Token => typeof(transitions.first[1].first[1])

How can I assign the output of typeof(transitions.first[1].first[1]) to a variable and use that variable everywhere like this

typ = typeof(transitions.first[1].first[1])

if transitions.is_a? Hash(State, Hash(Token, typ))
    return transitions
end

input_consequent_mapping = {} of Token => typ

When I do this , the compiler gives me error saying:

In src/finite.cr:45:52

 45 | if transitions.is_a? Hash(State, Hash(Token, typ))
                                                   ^
Error: unexpected token: "typ"

You already found out how to assign the result of typeof to a variable.

But you can’t use a variable as a type argument. The reason for that is that type arguments need to be known at compile time, while variables only exist at runtime.
So what you’re trying to do here doesn’t really work.

There may be alternative solutions. But that needs more information about the wider context and motivation.
Why do you want to do this? What purpose would it have in your program?

1 Like

One way to do it is by calling a helper method that captures the type. Something like:

helper(transitions, typeof(transitions.first[1].first[1]))

def helper(transitions, type : T.class) forall T
  if transitions.is_a? Hash(State, Hash(Token, T))
    return transitions
  end

  input_consequent_mapping = {} of Token => T
end

Well, I guess that’s the only way to do it.

3 Likes