This works:
struct Comic
endpoint::String
end
function Comic(id::Int)
url = "https://xkcd.com/$id/info.0.json"
Comic(url)
end
Comic(1)
It returns Comic("https://xkcd.com/1/info.0.json")
.
This doesn't work:
struct Comic
endpoint::String
end
function Comic(id::String)
url = "https://xkcd.com/$id/info.0.json"
Comic(url)
end
Comic("1")
It kills the Julia process.
Why doesn't the second example work?
Since none of the answers so far have actually explained what you are doing wrong - this occurs because you are trying to call a constructor of int and pass an argument. As you can see here, there is no int constructor that accepts a string argument (or any other type, for that matter).
A string is a sequence of characters. Sometimes we want to create a string object from different sources. For example, byte array, character array, StringBuffer, and StringBuilder. The String class constructors are provided to create a string object from these arguments. We can broadly classify string constructors into following categories.
String Constructor with StringBuffer Argument 9. String Constructor with StringBuilder Argument Why do we need String Constructors? We can create string object using double quotes. So why do we need so many constructors in String Class? A string is a sequence of characters. Sometimes we want to create a string object from different sources.
Without constructors, all objects will have the same values and no object will be unique. In languages such as Java and C++, constructors are created by defining a method with the same name as the Class.
In your code Comic("1")
calls Comic(id::String)
.
Comic(id::String)
calls Comic(url)
which again means calling Comic(id::String)
So you simply end up with an endless recursive loop.
The other answer explains why this crashes the Julia process; now, to make this work the way you intended, you can simply use an inner constructor:
julia> struct Comic
endpoint::String
Comic(id::String) = new("https://xkcd.com/$id/info.0.json")
end
julia> Comic("1")
Comic("https://xkcd.com/1/info.0.json")
This works because new
doesn't recursively call this constructor (which would lead to the crash). Instead it creates the object directly with the given string as its element.
Another option to consider is the URIs.jl package.
julia> using URIs
julia> struct XComic
endpoint::URI
end
julia> XComic(id::String) = XComic(URI("https://xkcd.com/$id/info.0.json"))
XComic
julia> XComic("4")
XComic(URI("https://xkcd.com/4/info.0.json"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With