How to refactor code which is using the fallback constructor


#1

Per the v0.7 what’s new:

The fallback constructor that calls convert is deprecated. Instead, new types should prefer to define constructors, and add convert methods that call those constructors only as necessary

What’s the recommended way to refactor code which relies on this behavior. Take this simple example - how should it be rewritten?

import Base.convert

struct Continent
  name::String
end

struct Country
  name::String 
  continents::Vector{Continent}
end

convert(Continent, x::String) = Continent(x)

c = Country("Turkey", ["Europe", "Asia"])

Thanks!


#2

Here’s one way to define your own fallback:

Country(name, continents) = Country(string(name), [Continent(x) for x in continents])

#3

Thank you

OK, so the idea is to define a “very” generic external constructor, which takes Any types of arguments where it makes sense – and explicitly convert these to the types expected by the default constructor.