sealed class DefaultsTo[A, B]
trait LowPriorityDefaultsTo {
implicit def overrideDefault[A,B] = new DefaultsTo[A,B]
}
object DefaultsTo extends LowPriorityDefaultsTo {
implicit def default[B] = new DefaultsTo[B, B]
}
Then, a parameterized method can be written as
def method[T](implicit e: T DefaultsTo String) = e
and `String` will be inferred instead of `Nothing` if no parameter is
specified. Similarly, a parameterized class can be written as
class C[T](implicit e: T DefaultsTo String)
[2] and [3] are some related questions on SO. I'd love to see this
get into the standard library, maybe with some supporting syntax
mirroring that of default parameters, like
def method[T = String] = // ... this syntax directly mirrors
default parameters
// or
def method[T =: String] = // ... reminiscent of default parameters,
but also `<:` and `>:`
~Aaron
[1] http://scala-programming-language.1934581.n4.nabble.com/Default-type-parameters-tt3169946.html
[2] http://stackoverflow.com/questions/6628849/default-type-for-method-calls
[3] http://stackoverflow.com/questions/4403906/is-it-possible-in-scala-to-force-the-caller-to-specify-a-type-parameter-for-a-pol
class Has[B] {
type AsDefault[A] = DefaultsTo[A, B]
}
def method[T : Has[String]#AsDefault] = // ...
I'm dredging up Richard Emberson's old (pre-Groups) thread [1] about
default type parameters here, but I thought this might be useful
enough to warrant sharing with the list. A dead-simple solution to
specifying a default type for a type parameter is to use this phantom
type:
sealed class DefaultsTo[A, B]
trait LowPriorityDefaultsTo {
implicit def overrideDefault[A,B] = new DefaultsTo[A,B]
}
object DefaultsTo extends LowPriorityDefaultsTo {
implicit def default[B] = new DefaultsTo[B, B]
}
Then, a parameterized method can be written as
def method[T](implicit e: T DefaultsTo String) = e
and `String` will be inferred instead of `Nothing` if no parameter is
specified. Similarly, a parameterized class can be written as
class C[T](implicit e: T DefaultsTo String)
[2] and [3] are some related questions on SO. I'd love to see this
get into the standard library, maybe with some supporting syntax
mirroring that of default parameters, like
def method[T = String] = // ... this syntax directly mirrors
default parameters
// or
def method[T =: String] = // ... reminiscent of default parameters,
but also `<:` and `>:`
~Aaron
[1] http://scala-programming-language.1934581.n4.nabble.com/Default-type-parameters-tt3169946.html
[2] http://stackoverflow.com/questions/6628849/default-type-for-method-calls
[3] http://stackoverflow.com/questions/4403906/is-it-possible-in-scala-to-force-the-caller-to-specify-a-type-parameter-for-a-pol