Hacker News new | past | comments | ask | show | jobs | submit login

> The challenge in Julia is that I might want to define that only objects of type `Shape` can be serialized, but if `Polygon` and `Circle` was not already defined as subtypes of `Shape` I cannot do anything about that without changing source code. Swift has an advantage in his case.

You can do this with traits. One pattern is that you can define

    struct Shape{T} end
    struct Not{T}   end

    has_shape_trait(::T) where {T} = Not{Shape}
    has_shape_trait(::Circle)      = IsShape{Circle}
    has_shape_trait(::Polygon)     = IsShape{Polygon}
and then you can write

   serialize(io::IO, x) = serialize(io, has_shape_trait(x), x)
   serialize(io::IO, ::Shape, x) = # shape serialization here
   serialize(io::IO, ::Not{Shape}, x) = # Fallback code, or an error here (or just leave it undefined)
This requires a bit more boiler-plate than regular abstract types but it's a pretty powerful technique (and has no runtime overhead). I do dream of having built in traits someday though to remove some of the boiler plate.

__________

By the way, is this a typo in your first paragraph?

> I am a big fan of Julia, but Swift is perhaps the only statically typed object-oriented language (apart from Objective-C) which I have found offers some similarity in flexibility to Swift's way of dealing with types.

You seem to be saying Swift is the only language which is similar in flexibility to Swift. Maybe you meant to reference another language?




Great example with the traits. Yes I seemed to have made a whole series of typos. Must have been tired then.

In this quote, I meant Julia and not Swift ;-)

" some similarity in flexibility to Swift's way of dealing with types."




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: