I'm trying to do the following
type Foo{T}
x::changeType(T)
end
where the function changeType
changes the type parameter to some other type. It doesn't have to be a function, I'm happy using a dictionary or a macro or w/e, I just need a way to do this.
I tried it with both a function and a dictionary and both resulted in errors.
I believe this is not entirely possible. However, you can play with a couple of workarounds.
Do not constrain the type of
x
and just instantiatex
with the proper type manualy:You can wrap your object in a function:
Then create an object of
Foo
If you want to have mixed type fields in the same
type
(e.g. fields ofT
andmap(T)
) you can modify a bit the constructor:This will allow you to create
Foo
asFoo{Int64}
while mappingx
toFloat32
:And the last, and probably the most viable one: first define the dictionary and wrap your
type
in bothtypes
:Now wrap the construction of a
Foo
object into a function:foo
function creates objects of typeFoo
where the first parameter specifies the typeT
ofFoo
and the typeV
is dynamically inferred from thetypes
dictionary.Note: in both the above methods, if
T
is not defined in thetypes
dictionary, theget
function returnsT
and thusx
is mapped toT
. Is a fall-back method for types that don't require mapping. E.g. for the third option:both
x
andy
areInt32
sinceInt32
is not in the mapping dicttypes
. And for the fourth option:I think currently the type of
x
cannot be specified at compile time as a function ofT
, but the above workarounds should do the job.I don't know neither how smart is the Julia compiler.. given that the
types
dictionary is constant, it might do some smart things and infer the type ofx
from there (maybe a dev could answer this or give further improvements).