Julia's singleton types are abstract types whose only instance is a single
type object. This is useful for writing methods that dispatch on type
values rather than on the type of an argument. They are abstract types –
they don't have fields and they don't hold data.

If you want an object to store some values, define a type and make a single
instance of it:

type CParam
  rho::Float64
  cc::Float64
end
const cparam = CParam(0,0)


Now use cparam as your "singleton" – if you don't want more than one
instance, don't create more than one.



On Tue, Jan 21, 2014 at 10:57 AM, Alexander Samoilov <
[email protected]> wrote:

> Hello Experts!
>
> After reading Julia docs on types it is still unclear for me how how to
> use singleton classes for common tasks, e.g. for packaging some common
> values.
>
> As a side note let me elaborate with the example from Scala programming
> language.
> Scala has intrinsic support for singletons - Objects.
>
> ```scala
> scala> object CParam {
>      | var rho: Double = 1.0
>      | var cc: Double = 1.0
>      | }
> defined module CParam
>
> scala> CParam.rho = 2.0
> CParam.rho: Double = 2.0
>
> scala> import CParam._
> import CParam._
>
> scala> rho
> res0: Double = 2.0
> ```
>
> Now trying to project it to Julia:
>
> ```jlcon
> julia> type CParam
>          rho::Float64
>          cc::Float64
>          function CParam()
>            new(0.0, 0.0)
>          end
>        end
>
> julia> x = CParam()
> CParam(0.0,0.0)
>
> julia> x.rho
> 0.0
> ```
>
> So good so far, though this is not a singleton, just an instance.
> The Julia documentation says that parametric Type{T} is a special
> parametric kind of the type T - the singleton type.
>
>
> ```jlcon
> julia> x = Type{CParam}
> Type{CParam}
>
> julia> x.rho
> ERROR: type DataType has no field rho
> ```
>
> Trying to exploit modules as model for singleton class (follow Fortran90 -
> it uses modules for information hiding and packaging).
>
> ```jlcon
> julia> module CParam
>             export rho, bulk, cc, zz
>             rho  = 1.0
>             bulk = 1.0
>             cc   = 1.0
>             zz   = 1.0
>        end
>
> julia> CParam.rho  = 2.0
> ERROR: cannot assign variables in other modules
> ```
> Could you please recommend a programming idiom better fitting to Julia?
>
> Thanks!
> Alexander
>
>

Reply via email to