Skip to content

Instantly share code, notes, and snippets.

@propensive
Created March 21, 2015 22:34
Show Gist options
  • Save propensive/adcc36edd145ff7d8371 to your computer and use it in GitHub Desktop.
Save propensive/adcc36edd145ff7d8371 to your computer and use it in GitHub Desktop.
`alloc`, an alternative to `new`, with better syntax and type inference
Welcome to Scala version 2.10.5 (OpenJDK 64-Bit Server VM, Java 1.6.0_27).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import rapture.core._
import rapture.core._
scala> val str: String = alloc() // new String()
str: String = ""
scala> val date: java.util.Date = alloc() // new java.util.Date()
date: java.util.Date = Sat Mar 21 23:33:20 CET 2015
scala> val sb = alloc[StringBuilder]() // new StringBuilder()
sb: StringBuilder =
scala> val exc: RuntimeException = alloc("Error message") // new RuntimeException("Error message")
exc: RuntimeException = java.lang.RuntimeException: Error message
scala> case class Tc[T](val default: T)
defined class Tc
// Particularly useful for removing repetition in an implicit's type and constructor call
scala> implicit val stringTc: Tc[String] = alloc("foo")
stringTc: Tc[String] = Tc@5e4d273a
scala>
@propensive
Copy link
Author

Yes, it's implemented with a macro.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment