In 2014 when I first learned about Julia, I also suggested on this
newsgroup that there should be a 'const' keyword as in C++ to annotate
function arguments and return variables that are supposed to be read-only.
Possibly you can find the old thread with google. I received a lot of
feedback from experienced Julia users and core developers that convinced me
that this is probably not a good idea. Here are some reasons that I can
recall from the earlier discussion that adding 'const' to Julia may not be
a good idea.
(1) The 'const' keyword would make the multiple-dispatch system much more
confusing because it would entail new rules about how the 'const' keyword
affects closeness in the type hierarchy.
(2) You can already get the desired effect in Julia by defining your own
subtype of DenseArray in which getindex works as usual but setindex! throws
an error.
(3) The promise that a routine won't change a 'const' argument could easily
be defeated by aliasing (i.e., a function is invoked with a const argument,
but another non-const argument refers to the same piece of data), so it may
give the user a false sense of security.
-- Steve Vavasis
On Monday, October 26, 2015 at 10:29:34 PM UTC-4, Carlo Lucibello wrote:
>
> It would be nice to annotate the return type of methods with a constant
> qualifier, in order to have
> an efficient and safe behaviour at the same time.
>
> I mean something like this:
>
> type A
> data::Vector{Int}
> end
>
> # invalid but desiderable julia code
> const function getdata(a::A)
> return a.data
> end
>
> a = A(ones(10))
> data = getdata(a)
>
> data[1] = 2 # ERROR
> a.data[1] = 2 # OK
>
>