Crystal (programming language): Difference between revisions

Content deleted Content added
Type Inference and Union Types: The provided example was just wrong and generally terrible
Line 45:
 
===Type Inference and Union Types===
The following code defines an array containing different types with no usable common ancestor. Crystal automatically creates a union type out of the types of the individual items.
 
In the following code sample, there is no need to specify the type of method argument '''''a''''', which will be inferred to be of a union type of all types provided to the '''''print_max''''' function.
 
<syntaxhighlight lang="ruby">
desired_things = [:unicorns, "butterflies", 1_000_000]
def print_max(*a)
p typeof(desired_things.first) # typeof returns the compile time type, here (Int32 | String | Symbol)
# The splat '*' indicates a vararg and print_max is a variadic function
p desired_things.first.class # the class method returns the runtime type, here Symbol
# that takes a tuple of any size.
puts("#{a.max}") # Notice the use of string interpolation
end
 
print_max(5, 6, 3, 4.3, 9, 10, 7.9) # type of Array(Float64 | Int32)
print_max("lion", "rhinoceros", "zebra", "elephant") # type of Array(String)
print_max('1', 'a', 'i', '9') # type of Array(Char)
</syntaxhighlight>
 
The code sample above prints 10, zebra, and i.
 
===Concurrency===