Hey, consider following snippet with types declared with Constructor function:
without_block = Types.Constructor(String)
without_block[123] # Dry::Types::CoercionError (no implicit conversion of Integer into String)
without_block['abc'] # 'abc'
without_block['123'] # '123'
with_block = Types.Constructor(String) { |value| Integer(value) }
with_block[123] # 123
with_block['abc'] # Dry::Types::CoercionError (invalid value for Integer(): "abc")
with_block['123'] # 123
Types.Constructor { |value| Integer(value) } # ArgumentError (wrong number of arguments (given 0, expected 1..2))
- Type
with_blockreturnsInteger, which is kind of obvious because provided block returnsInteger. - Type
with_blockaccepts both123and'123'because it’s being passed straight to the block. - You can’t use
Constructormethod only with block, without a type.
Given that, my question is:
What is the purpose of providing a type to the Constructor function when block is given?