Created
April 22, 2015 07:05
-
-
Save davidhoyt/59343ccbc85fc8c1a27c to your computer and use it in GitHub Desktop.
Wrapper for by-name expressions to make them eligible for implicit resolution and implicit conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Provides a wrapper for by-name expressions with the intent that they can become eligible for | |
* implicit conversions and implicit resolution. | |
* | |
* @param expression A by-name parameter that will yield a result of type `T` when evaluated. | |
* @tparam T Result type of the evaluated `expression`. | |
*/ | |
final class ByName[+T](expression: => T) extends (() => T) { | |
/** | |
* Evaluates the given `expression` every time <em>without</em> memoizing the result. | |
* | |
* @return Result of type `T` when evaluating the provided `expression`. | |
*/ | |
def apply(): T = expression | |
/** | |
* Lazily maps the given expression of type `T` to type `U`. | |
*/ | |
def map[U](fn: T => U): ByName[U] = | |
ByName[U](fn(expression)) | |
} | |
object ByName { | |
import scala.language.implicitConversions | |
/** | |
* Implicitly converts a by-name `expression` of type `T` into an instance of [[ByName]]. | |
*/ | |
implicit def apply[T](expression: => T): ByName[T] = | |
new ByName(expression) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment