object GoodReturnType extends Dynamic {
def applyDynamic(method: String)(args: Any*) = {
method match {
case "foo" => 25
case "bar" => 14
}
}
}
Method applyDynamic of GoodReturnType object has Int return type. As expected, invocations of its dynamic methods return Int too.
scala> GoodReturnType.foo()
res0: Int = 25
If we try to add another dynamic method with different return type, return type of applyDynamic will be most common type (which is Any). So as all dynamic methods.
object BadReturnType extends Dynamic {
def applyDynamic(method: String)(args: Any*) = {
method match {
case "foo" => 25
case "bar" => 14
case "baz" => "muahahaha!"
}
}
}
scala> BadReturnType.foo()
res1: Any = 25
Is it possible to have a class with multiple dynamic methods with different return types?
This is not possible in principle because you are dispatching based on dynamic information. Thus, even if you had a response that was typed a particular way, the calling code wouldn’t know which type was returned from the available set. You can use
Eitherto express this explicitly if you want (e.g.Left(5)andRight("muahaha")would returnEither[Int,String]), but fundamentally you can’t retain your static typing after going through a dynamic dispatch step. If you’re not going to use this as a dynamic dispatch step, why not just put the method in directly?