Permalink
Browse files

Added apply method to Box

  • Loading branch information...
jqno committed Feb 19, 2012
1 parent cc68695 commit de5de84c3a14d6ed0c77120290fc1835092d2de5
Showing with 46 additions and 0 deletions.
  1. +14 −0 src/main/scala/com/nummulus/boite/Box.scala
  2. +32 −0 src/test/scala/com/nummulus/boite/BoxTest.scala
@@ -70,6 +70,20 @@ sealed abstract class Box[+A] {
}
}
+object Box {
+ /**
+ * A Box factory which returns a Full(f) if f is not null, Empty if it is,
+ * and a Failure if f throws an exception.
+ */
+ def apply[A](f: => A): Box[A] = try {
+ val value = f
+ if (value == null) Empty else Full(value)
+ }
+ catch {
+ case e: Exception => Failure(e)
+ }
+}
+
final case class Full[+A](value: A) extends Box[A] {
def isEmpty = false
@@ -0,0 +1,32 @@
+package com.nummulus.boite
+
+import org.scalatest.FlatSpec
+import org.junit.runner.RunWith
+import org.scalatest.matchers.ShouldMatchers
+import org.scalatest.junit.JUnitRunner
+
+@RunWith(classOf[JUnitRunner])
+class BoxTest extends FlatSpec with ShouldMatchers {
+ val GilbertBecaud = "Gilbert Bécaud"
+ val NotSupported = "not supported"
+ val Exception = new UnsupportedOperationException(NotSupported)
+ val Error = new AssertionError
+
+ "apply" should "return Empty when it is passed null" in {
+ Box(null) should be (Empty)
+ }
+
+ it should "return Full(value) when it is passed a value" in {
+ Box(GilbertBecaud) should equal (Full(GilbertBecaud))
+ }
+
+ it should "return Failure when an exception is thrown while evaluating the expression passed to it" in {
+ Box(throw Exception) should equal (Failure("not supported", Full(Exception)))
+ }
+
+ it should "let Errors pass through" in {
+ intercept[AssertionError] {
+ Box(throw Error)
+ }
+ }
+}

0 comments on commit de5de84

Please sign in to comment.