txt: ## coercion-20type.md
  Coercion type
  
  Combined from primary sources listed below.
  
  # [In Signature literals](#___top "go to top of document")[§](#(Signature_literals)_Coercion_type_Coercion_type "direct link")
  
  See primary documentation
  [in context](/language/signatures#Coercion_type)
  for **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`](/type/Any) it can be omitted.
  
  ```raku
  sub f(Int(Str) $want-int, Str() $want-str) {
      say $want-int.^name ~ ' ' ~ $want-str.^name
  }
  f '10', 10;
  # OUTPUT: «Int Str␤»
  
  sub foo(Date(Str) $d) { say $d.^name; say $d };
  foo "2016-12-01";
  # OUTPUT: «Date␤2016-12-01␤»
  ```
  
  The coercion is performed by calling the method with the name of the type to coerce to, if it exists. In this example, we're calling the builtin method [`Date`](/type/Date) on the [`Str`](/type/Str) class. 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:
  
  ```raku
  sub square-str (Int $x --> Str(Int)) {
      $x²
  }
  
  for 2,4, *²  … 256 -> $a {
      say $a, "² is ", square-str( $a ).chars, " figures long";
  }
  
  # 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 [`Str`](/type/Str) allows us to directly apply string methods, such as the number of characters.
  
  **Note**: The appropriate method must be available on the argument, so be careful when trying to coerce custom types.
  
  ```raku
  class Foo { }
  
  sub bar(Foo(Int) $x) { say $x }
  
  bar(3);
  # OUTPUT: «Impossible coercion from 'Int' into 'Foo': no acceptable coercion method found␤»
  
  ```
  