Skip to content

Instantly share code, notes, and snippets.

@igstan
Last active August 29, 2015 14:06
Show Gist options
  • Save igstan/b800988ddfc05cb44ec3 to your computer and use it in GitHub Desktop.
Save igstan/b800988ddfc05cb44ec3 to your computer and use it in GitHub Desktop.
trait Default[T] {
@inline
def default: T
}
object Default {
implicit val intDefault: Default[Int] = apply(0)
implicit val byteDefault: Default[Byte] = apply(0)
implicit val shortDefault: Default[Short] = apply(0)
implicit val longDefault: Default[Long] = apply(0L)
implicit val floatDefault: Default[Float] = apply(0.0F)
implicit val doubleDefault: Default[Double] = apply(0.0)
implicit val booleanDefault: Default[Boolean] = apply(false)
implicit def otherDefault[T <: AnyRef]: Default[T] =
// Please not that this call does not rely on the current behaviour
// of v.asInstanceOf[T] when v is null and T is an AnyVal instance.
apply(null.asInstanceOf[T])
@inline
def of[T](implicit D: Default[T]): T = D.default
@inline
private def apply[T](t: T) = new Default[T] { def default = t }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment