Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created December 14, 2010 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmizu/740318 to your computer and use it in GitHub Desktop.
Save kmizu/740318 to your computer and use it in GitHub Desktop.
trait DefaultValue[T] {
def value: T
}
object DefaultValue {
implicit object DefaultByteValue extends DefaultValue[Byte] {
def value: Byte = 0
}
implicit object DefaultShortValue extends DefaultValue[Short] {
def value: Short = 0
}
implicit object DefaultCharValue extends DefaultValue[Char] {
def value: Char = 0
}
implicit object DefaultIntValue extends DefaultValue[Int] {
def value: Int = 0
}
implicit object DefaultLongValue extends DefaultValue[Long] {
def value: Long = 0L
}
implicit object DefaultFloatValue extends DefaultValue[Float] {
def value: Float = 0.0f
}
implicit object DefaultDoubleValue extends DefaultValue[Double] {
def value: Double = 0.0
}
implicit object DefaultBooleanValue extends DefaultValue[Boolean] {
def value: Boolean = false
}
private val defaultValueCache = new DefaultValue[AnyRef] {
def value: AnyRef = null
}
//To avoid creation of DefaultValue[AnyRef] instance.
implicit def DefaultAnyRef[T >: Null <: AnyRef]: DefaultValue[T] = {
defaultValueCache.asInstanceOf[DefaultValue[T]]
}
def default[T:DefaultValue]: T = implicitly[DefaultValue[T]].value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment