JohnyBe
JohnyBe

Reputation: 323

Julia types with abstract type and definied type

How to make type with one abstract and one definied field

Like this:

abstract AbstractType 

type type1 <: AbstractType
    x
    y
end

type type2 <: AbstractType
    w 
    z 
end

type MyType{T<:AbstractType}
         a::T
         b::Int64
 end

a = MyType(type1(1,2))

I tried with some constructors but it didnt work as well.

Upvotes: 0

Views: 141

Answers (2)

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22255

It's not clear what you're trying to do. The reason your last statement isn't working has less to do with mixed types and more to do with the fact that you're trying to instantiate your type while missing an input argument.

If you want to be able to instantiate with a default value for b, define an appropriate wrapper constructor:

abstract AbstractType
type type1 <: AbstractType; x; y; end
type type2 <: AbstractType; w; z; end
type MyType{T<:AbstractType}; a::T; b::Int64; end
MyType{T<:AbstractType}(t::T) = MyType(t,0);   # wrapper

julia> a = MyType(type1(1,2))
  MyType{type1}(type1(1, 2), 0)

Upvotes: 4

Chris Rackauckas
Chris Rackauckas

Reputation: 19162

You need MyType to be a type with just one field, and allow that field to hold a type1 (or two). That is:

type MyType{T<:AbstractType}
         a::T
end

Upvotes: 1

Related Questions