syntax Coercion type
Documentation for syntax Coercion type
assembled from the following types:
class Signature
From Signature
(Signature) Coercion type
To accept one type but coerce it automatically to another, use the accepted type as an argument to the target type. If the accepted type is Any
it can be omitted.
sub f(Int(Str) , Str() )f '10', 10;# OUTPUT: «Int Str»use MONKEY;augment ;sub foo(Date(Str) ) ;foo "2016-12-01";# OUTPUT: «Date2016-12-01»
The coercion is performed by calling the method with the name of the type to coerce to, if it exists (e.g. Foo(Bar)
coercer, would call method Foo
). The method is assumed to return the correct type—no additional checks on the result are currently performed.
Coercion can also be performed on return types:
sub square-str (Int --> Str(Int))for 2,4, *² … 256 -># OUTPUT: «2² is 1 figures long# 4² is 2 figures long# 16² is 3 figures long# 256² is 5 figures long»
In this example, coercing the return type to String
allows us to directly apply string methods, such as the number of characters.