Currently the keyword "typeof" is used to get type from a class literal. How about extending its functionality to extract type of expression? E.g.
val typeof(TheClass.methodWithComplicatedReturnType) result = ...
val List<typeof(TheClass.methodWithComplicatedReturnType)> results = newArrayList
This idea comes from my experience of an actual project, which is like this:
def methodWithComplicatedReturnType() {
return 1 -> "a" -> true -> new ArrayList<String>
}
def collectComplicatedResults() {
val result = methodWithComplicatedReturnType // So far so good; the type of result is automatically inferred from the method
val List<????> results = newArrayList // Now I want to collect multiple results into a list.
// What's type of the list......
(0..<100).forEach[
results.add(methodWithComplicatedReturnType)
]
results.get(0). ..... // To use the elements of results, I have to know its accurate type,
// which cannot be inferred directly.
// Of course I can figure the type out manually, But that is cumbersome and error prone,
// not to mention it has to be in sync with the return expression
}
Actually I figured out a workaround:
def static <T, L extends List<T>, DUMMY> listOfType(Class<L> listClass, (DUMMY)=>T dummy) {
return listClass.newInstance as List<T> // I want type of returned list to be List, not ArrayList
}
Then I can write:
val results = listOfType(ArrayList) [methodWithComplicatedReturnType]
Yes it can do the automatic type inferrence trick, but it also has flaws: It is hard to provide arguments to constructor of ArrayList, and I have to write more setOfType/mapOfType... methods for any possible structure needing complicated type as generic parameter.
So I wonder if we can use already existent keyword "typeof" to extract type of an expression, which can be used like this:
val typeof(TheClass.methodWithComplicatedReturnType) result = ...
val List<typeof(TheClass.methodWithComplicatedReturnType)> results = newArrayList
I think this can address above problem naturally. And I believe it has more power that I just yet to figure out...