Is it possible in Scala to force the caller to specify a type parameter for a polymorphic method ?
- by Alex Kravets
//API
class Node
class Person extends Node
object Finder
{
def find[T <: Node](name: String): T = doFind(name).asInstanceOf[T]
}
//Call site (correct)
val person = find[Person]("joe")
//Call site (dies with a ClassCast inside b/c inferred type is Nothing)
val person = find("joe")
In the code above the client site "forgot" to specify the type parameter, as the API writer I want that to mean "just return Node". Is there any way to define a generic method (not a class) to achieve this (or equivalent). Note: using a manifest inside the implementation to do the cast if (manifest != scala.reflect.Manifest.Nothing) won't compile ... I have a nagging feeling that some Scala Wizard knows how to use Predef.<:< for this :-)
Ideas ?