typeof¶
typeof
表達式會回傳表達式的型別
a = 1
b = typeof(a) # => Int32
它接受多個引數,而結果是表達式型別的聯集
typeof(1, "a", 'a') # => (Int32 | String | Char)
它常被用於泛型程式碼中,以利用編譯器的型別推論能力
hash = {} of Int32 => String
another_hash = typeof(hash).new # :: Hash(Int32, String)
由於 typeof
並不會實際評估表達式,因此它可以在編譯時期用於方法,例如這個範例,它會遞迴地從巢狀泛型型別形成聯集型別
class Array
def self.elem_type(typ)
if typ.is_a?(Array)
elem_type(typ.first)
else
typ
end
end
end
nest = [1, ["b", [:c, ['d']]]]
flat = Array(typeof(Array.elem_type(nest))).new
typeof(nest) # => Array(Int32 | Array(String | Array(Symbol | Array(Char))))
typeof(flat) # => Array(String | Int32 | Symbol | Char)
這個表達式也可用於型別語法。