as

as

The as pseudo-method restricts the types of an expression. For example:

if some_condition
  a = 1
else
  a = "hello"
end

# a : Int32 | String

In the above code, a is a union of Int32 | String. If for some reason we are sure a is an Int32 after the if, we can force the compiler to treat it like one:

a_as_int = a.as(Int32)
a_as_int.abs          # works, compiler knows that a_as_int is Int32

The as pseudo-method performs a runtime check: if a wasn't an Int32, an exception is raised.

The argument to the expression is a type.

If it is impossible for a type to be restricted by another type, a compile-time error is issued:

登录查看完整内容