Martin,

If you want to implement file loading, and you care that only entities of 
type File get accepted through the loading function's function signature 
(excluding the Type File as an accepted entity), Julia does that naturally.
All you were overlooking is the part where an actual File entity is 
constructed by applying a concrete type. 

abstract AbstractFile

immutable ConcreteFile <: AbstractFile 
    fileSpecs ..
end

function fileLoader{F<:AbstractFile}(file::F)
    loadfile(f)
end

myFileDescriptor = ConcreteFile( filespecs... )

myFileContents = fileLoader( myFileDescriptor )

# fileLoader( AbstractFile, .. ) will throw an error 
# fileLoader( ConcreteFile, .. ) will throw an error
# fileLoader( myFileDescriptor ) will not







On Thursday, April 7, 2016 at 7:34:52 AM UTC-4, Martin Kuzma wrote:
>
> 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.
>
>
>
>
>

Reply via email to