I would like to know how if it is possible to have a default type when calling a type-parameterized method in Scala. Suppose I have the following method somewhere:
def apply[A]( id: String )( implicit processor: Processor[A] ) =
processor( data get id )
I would like A to be String, when the compiler has no hints about what type to infer. So I can overload my definition with:
def apply( id: String )( implicit processor: Processor[String] ) =
processor( data get id )
But both methods will have the same signature after erasure… Is there any way to provide a default type ?
You can achieve this by defining the following phantom type:
Then your method can be written
The definition of
overrideDefaultguarantees that for any two specified types,AandB, the compiler can always supply an object of typeDefaultsTo[A, B](e.g.DefaultsTo[Int, String]). However, if one of the two types are unspecified (e.g.DefaultsTo[A, String]), the compiler will prefer to identify the two types (supplying, in the example,DefaultsTo[String, String], and thus inferringStringfor the unspecified typeA).As Naftoli Gugenheim pointed out in this mailing list thread, you can also achieve some nice syntax for use with context bounds: