Skip to content

Commit 3dcd0ae

Browse files
authored
Merge pull request #541 from pedorich-n/option-companion-object-methods
Option.when and Option.unless added
2 parents 7a1171d + ed5116d commit 3dcd0ae

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

compat/src/main/scala-2.11_2.12/scala/collection/compat/PackageShared.scala

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,9 @@ private[compat] trait PackageShared {
282282
implicit def toMapViewExtensionMethods[K, V, C <: scala.collection.Map[K, V]](
283283
self: IterableView[(K, V), C]): MapViewExtensionMethods[K, V, C] =
284284
new MapViewExtensionMethods[K, V, C](self)
285+
286+
implicit def toOptionCompanionExtension(fact: Option.type): OptionCompanionExtensionMethods =
287+
new OptionCompanionExtensionMethods(fact)
285288
}
286289

287290
class ImmutableSortedMapExtensions(private val fact: i.SortedMap.type) extends AnyVal {
@@ -587,3 +590,9 @@ class MutableQueueExtensionMethods[Element](private val self: m.Queue[Element])
587590
def enqueueAll(iter: c.Iterable[Element]): Unit =
588591
self.enqueue(iter.toIndexedSeq: _*)
589592
}
593+
594+
class OptionCompanionExtensionMethods(private val fact: Option.type) extends AnyVal {
595+
def when[A](cond: Boolean)(a: => A): Option[A] = if (cond) Some(a) else None
596+
597+
@inline def unless[A](cond: Boolean)(a: => A): Option[A] = when(!cond)(a)
598+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
* Scala (https://www.scala-lang.org)
3+
*
4+
* Copyright EPFL and Lightbend, Inc.
5+
*
6+
* Licensed under Apache License 2.0
7+
* (http://www.apache.org/licenses/LICENSE-2.0).
8+
*
9+
* See the NOTICE file distributed with this work for
10+
* additional information regarding copyright ownership.
11+
*/
12+
13+
package test.scala.collection
14+
15+
import scala.collection.compat._
16+
import org.junit.Test
17+
import org.junit.Assert._
18+
19+
class OptionTest {
20+
21+
private val value: String = "example"
22+
private val some: Option[String] = Some(value)
23+
private val none: Option[String] = None
24+
25+
@Test
26+
def testWhenTrue: Unit = {
27+
val option = Option.when(true)(value)
28+
assertEquals(option, some)
29+
}
30+
31+
@Test
32+
def testWhenFalse: Unit = {
33+
val option = Option.when(false)(value)
34+
assertEquals(option, none)
35+
}
36+
37+
@Test
38+
def testUnlessTrue: Unit = {
39+
val option = Option.unless(true)(value)
40+
assertEquals(option, none)
41+
}
42+
43+
@Test
44+
def testUnlessFalse: Unit = {
45+
val option = Option.unless(false)(value)
46+
assertEquals(option, some)
47+
}
48+
}

0 commit comments

Comments
 (0)