Subtyping parametric composite types

parametric-types

#1

I am struggling to understand how I can reuse methods which have been defined as composite parametric types. I am working with the LinearMaps.jl package which defines a FunctionMap as

struct FunctionMap{T,F1,F2} <: LinearMap{T}
    f::F1
    fc::F2
    M::Int
    N::Int
    _ismutating::Bool
    _issymmetric::Bool
    _ishermitian::Bool
    _isposdef::Bool
end

What I would like to do is create my own map which shares the same fields and methods as a FunctionMap, but to which I can add other methods (e.g. an inverse). For example, I would like to do something like this

import Base: \
struct MyMap{T,F1,F2} <: FunctionMap{T,F1,F2}
    f::F1
    fc::F2
    M::Int
    N::Int
    _ismutating::Bool
    _issymmetric::Bool
    _ishermitian::Bool
    _isposdef::Bool
end
\(A::MyMap, b::AbstractVector) = myinverse(A, b)

where MyMap inherits all methods from FunctionMap except \, which I define myself. The above code does not work, and I get a complaint of LoadError: LoadError: invalid subtyping in definition of MyMap.

Any suggestions?


#2

You can only subtype from abstract types. Besides reading the manual, maybe these posts can give some insights https://discourse.julialang.org/search?q=composition%20inheritance.


#3

For some more relevant information on why this is intentionally disallowed, see the Types section in the manual:

One particularly distinctive feature of Julia’s type system is that concrete types may not subtype each other: all concrete types are final and may only have abstract types as their supertypes. While this might at first seem unduly restrictive, it has many beneficial consequences with surprisingly few drawbacks. It turns out that being able to inherit behavior is much more important than being able to inherit structure, and inheriting both causes significant difficulties in traditional object-oriented languages.


#4

Yes it’s a good idea and the problem is that the library should be dispatching on an abstract type. I didn’t want to keep asking for it, but please revive the issue. Or just PR the solution.


#5

Thanks both of you. For now I have just copied the methods, but I will take this up with the developer or LinearMaps.jl


#6

I missed that paragraph in the manual and was puzzling over the “invalid subtyping” error, because I tried to subtype from a concrete type. Can the compiler message be made more specific?