I’d prefer to write multiple outer constructors for structs, so that the user can provide what they have and let the constructor make whatever conversions are needed. Running the mwe:
module ConstructorTest
struct Fraction
numerator::Integer
denominator::Integer
value::Number
name::String
end
Fraction(; numerator::Integer, denominator::Integer, name="") = Fraction(numerator, denominator, numerator/denominator, name)
Fraction(; value::Number, denominator::Integer, name="") = Fraction(value*denominator, denominator, value, name)
function test()
fa = Fraction(3,4,0.75,"three-quarters")
println(fa)
fb = Fraction(numerator=3,denominator=4,name="three-quarters")
println(fb)
fc = Fraction(value=0.75,denominator=4,name="three-quarters")
println(fc)
end
end
ConstructorTest.test()
I receive:
Main.ConstructorTest.Fraction(3, 4, 0.75, "three-quarters")
ERROR: LoadError: UndefKeywordError: keyword argument value not assigned
from fb’s creation. Despite using named arguments and unique argument types, the wrong constructor is called.
Have I made an error in defining the outer constructors or is this usage not intended/implemented?