Hello,
Lets say I want to somehow implement loading of a file. I have used only
dummy types for simplicity.
The first experiment:
abstract File
immutable FileA <: File end
immutable FileB <: File end
function load{F <: File}(t::Type{F}, path::ASCIIString)
ios::IOStream = open(path, "r")
f::File = load(t, ios)
close(ios)
f
end
load(::Type{FileA}, ios::IOStream) = FileA()
load(::Type{FileB}, ios::IOStream) = FileB()
This implementation works great, but it allows the user to pass the
abstract type File to the function load, because of File <: File. Is there
a way to allow only concrete types of File for function load?
I could use:
if typeof(t) == File
error("Not allowed.")
end
But without it, it's much cleaner.
So comming from OOP backgroud i used this:
abstract File
immutable FileA <: File end
immutable FileB <: File end
abstract FileLoader
immutable FileALoader <: FileLoader end
immutable FileBLoader <: FileLoader end
function load(l::FileLoader, path::ASCIIString)
ios::IOStream = open(path, "r")
f::File = load(l, ios)
close(ios)
f
end
load(l::FileALoader, ios::IOStream) = FileA()
load(l::FileBLoader, ios::IOStream) = FileB()
This code works as desired. Since instances of abstract types cant be
created. But it requires creation of empty objects that do nothing.
The first code is better suited for julia as types are only data
containers. I think :D That brings me to my question:
Is there a way to allow only concrete types of abstract supertype for
parametric function such as:
load{F <: File}(t::Type{F}, path::ASCIIString)
Thanks Martin.