Multiple return types dream

Suppose you want to do something like a set of preferences that are a simple key/value pairing.

A dictionary seems a great choice. Its keys can be any type and the values any type because both are variants.

So far so good.

Now you can do something like

dim i as integer = PrefsDict.Value("keyForIntegerValuedPreference")

And all seems great ! i gets an integer value and life is good

Except that this is ALSO legitimate

dim s as string = PrefsDict.Value("keyForIntegerValuedPreference")

And now your “strongly typed” system is fubarred. And the Xojo compiler will not complain

So how are you going to get an integer from something that SHOULD be an integer, and a string from something that should be a string ?
And get the compiler to help you do this ?

If you just use a dictionary you wont be able to. Its accessors dont have that capability.

You could try

GetValue(extends d as dictionary, key as variant) as Integer
GetValue(extends d as dictionary, key as variant) as String

but it wont work. Xojo doesn’t support multiple methods with the same signature and only differeing in return type 🙁

So how could you do this AND get the compiler to help you out ? What if instead of return values (which I will admit would be nicer) you do

GetValue(extends d as dictionary, key as variant, byref value as Integer)
GetValue(extends d as dictionary, key as variant, byref value as String)

and so on for every type ?

Now the compiler will tell you when you try to do something unsupported.
In our example with only integer and string values supported if we did

dim d as double
PrefsDict.GetValue("keyForIntegerValuedPreference", d)

the compiler would tell us this isnt supported

Its about the best we can hope for until/unless Xojo alters the compiler to permit several return types (and does the correct work to make use of it) In theory Xojo could make it so the compiler matched the right signature with the right return type to whatever is expected (like the following)

Dim i as integer = PrefsDict.GetValue("keyForIntegerValuedPreference") // would call the integer returning version
dim s as string = PrefsDict.GetValue("keyForStringValuedPreference") // would call the String returning version

2 Replies to “Multiple return types dream”

  1. Can’t you get vartype which tells you the original type stuffed into a varient? so you could check if requested type is consistent with what was put in it?
    -Karen

  2. You could return a PrefQueryObject with the key name, which then has Operator_Convert to fetch the value in the right data type.
    Then a single GetValue() should work.

    You may also recycle the PrefQueryObject object, so you only need one instance at a time.

Comments are closed.