struct Union(*T)

Overview

A union type represents the possibility of a variable or an expression having more than one possible type at compile time.

When invoking a method on a union type, the language checks that the method exists and can be resolved (typed) for each type in the union. For this reason, adding instance methods to Union makes no sense and has no effect. However, adding class method to Union is possible and can be useful. One example is parsing JSON into one of many possible types.

Union is special in that it is a generic type but instantiating it might not return a union type:

Union(Int32 | String)      # => (Int32 | String)
Union(Int32)               # => Int32
Union(Int32, Int32, Int32) # => Int32

Defined in:

union.cr

Class Method Summary

Instance methods inherited from struct Value

==(other) ==, dup dup

Instance methods inherited from class Object

!=(other) !=, !~(other) !~, ==(other) ==, ===(other : JSON::Any)
===(other : YAML::Any)
===(other)
===
, =~(other) =~, class class, dup dup, hash hash, inspect(io : IO)
inspect
inspect
, itself itself, not_nil! not_nil!, pretty_inspect(width = 79, newline = "\n", indent = 0) : String pretty_inspect, pretty_print(pp : PrettyPrint) : Nil pretty_print, tap(&block) tap, to_json(io : IO)
to_json
to_json
, to_pretty_json(indent : String = " ")
to_pretty_json(io : IO, indent : String = " ")
to_pretty_json
, to_s
to_s(io : IO)
to_s
, to_yaml(io : IO)
to_yaml
to_yaml
, try(&block) try

Class methods inherited from class Object

from_json(string_or_io, root : String) : self
from_json(string_or_io) : self
from_json
, from_yaml(string_or_io) : self from_yaml

Class Method Detail

def self.new(pull : JSON::PullParser) #

[View source]
def self.new(pull : YAML::PullParser) #

[View source]
def self.new #

[View source]
def self.nilable? #

Returns true if this union includes the Nil type.

(Int32 | String).nilable? # => false
(Int32 | Nil).nilable?    # => true

[View source]