Is it possible in Scala to force the caller to specify a type parameter for a polymorphic method ?

Posted by Alex Kravets on Stack Overflow See other posts from Stack Overflow or by Alex Kravets
Published on 2010-12-09T22:47:10Z Indexed on 2011/01/02 19:53 UTC
Read the original article Hit count: 135

Filed under:
|
|
//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 ?

© Stack Overflow or respective owner

Related posts about generics

Related posts about scala