ahm5
ahm5

Reputation: 683

julia subtype logic does not make any sense to me

I am using map on a subtype but it does not seems to work and I always get the error message. is anything wrong with my code or just I used the map function incorrectly .and I cant get really the Type, Subtype and the constructor logic in Julia. Thanx in advance

abstract type AbstractModel end


function validator(::Type{T}) where {T<:AbstractModel}
     #fieldtype(T,1)<:Type ||error("Validation error for type of default"," in the Type $T accure the error") 
     fieldtype(T,3)<:String ||error("Validation error for type of default"," in the Type $T accure the error"  )
     fieldtype(T,4)<:Int||error("Validation error for type of default"," in the Type $T accure the error"  ) 
     fieldtype(T,5)<:Int ||error("Validation error for type of default"," in the Type $T accure the error"  ) 
end

struct Field5 <:AbstractModel
    type
    default
    description
    min
    max
    Field5(type,default,description,min,max)=new("","","this is descriptio",7,10)
end

map(validator, subtypes(AbstractModel))

Upvotes: 0

Views: 161

Answers (1)

BatWannaBe
BatWannaBe

Reputation: 4510

It kind of looks like you just want to give fields types that you don't know in advance and restrict those types, you can do that with parameters:

struct Field5{A<:Type,
              B<:Any,
              C<:String, 
              D<:Int,
              E<:Int}
    type::A
    default::B
    description::C
    min::D
    max::E
end

x1 = Field5(Float64,"b","c",7,10) # works
x2 = Field5(Float64,"b","c",7,1.0) # MethodError because 1.0 is not <: Int

Alternatively, if you didn't want to restrict the types but only check it with validator, then you do this:

struct Field5{A,B,C,D,E}
    type::A
    default::B
    description::C
    min::D
    max::E
end

function validator(::Type{T}) where {T<:Field5}
     fieldtype(T,1)<:Type ||error("Validation error for type of default"," in the Type $T accure the error") 
     fieldtype(T,3)<:String ||error("Validation error for type of default"," in the Type $T accure the error"  )
     fieldtype(T,4)<:Int||error("Validation error for type of default"," in the Type $T accure the error"  ) 
     fieldtype(T,5)<:Int ||error("Validation error for type of default"," in the Type $T accure the error"  ) 
end

x1 = Field5(Float64,"b","c",7,10) # works
x2 = Field5(Float64,"b","c",7,1.0) # works

# note that x1 and x2 have different concrete types; Field5 is abstract
# now validator can tell if a concrete type fits its criteria

validator(typeof(x1)) # true
validator(typeof(x2)) # Validation error because 1.0 is not <:Int

Upvotes: 1

Related Questions