diff --git a/compat/src/main/scala-2.11_2.12/scala/collection/compat/PackageShared.scala b/compat/src/main/scala-2.11_2.12/scala/collection/compat/PackageShared.scala index 534f8948..b905aa02 100644 --- a/compat/src/main/scala-2.11_2.12/scala/collection/compat/PackageShared.scala +++ b/compat/src/main/scala-2.11_2.12/scala/collection/compat/PackageShared.scala @@ -282,6 +282,9 @@ private[compat] trait PackageShared { implicit def toMapViewExtensionMethods[K, V, C <: scala.collection.Map[K, V]]( self: IterableView[(K, V), C]): MapViewExtensionMethods[K, V, C] = new MapViewExtensionMethods[K, V, C](self) + + implicit def toOptionCompanionExtension(fact: Option.type): OptionCompanionExtensionMethods = + new OptionCompanionExtensionMethods(fact) } class ImmutableSortedMapExtensions(private val fact: i.SortedMap.type) extends AnyVal { @@ -587,3 +590,9 @@ class MutableQueueExtensionMethods[Element](private val self: m.Queue[Element]) def enqueueAll(iter: c.Iterable[Element]): Unit = self.enqueue(iter.toIndexedSeq: _*) } + +class OptionCompanionExtensionMethods(private val fact: Option.type) extends AnyVal { + def when[A](cond: Boolean)(a: => A): Option[A] = if (cond) Some(a) else None + + @inline def unless[A](cond: Boolean)(a: => A): Option[A] = when(!cond)(a) +} diff --git a/compat/src/test/scala/test/scala/collection/OptionTest.scala b/compat/src/test/scala/test/scala/collection/OptionTest.scala new file mode 100644 index 00000000..e81dfdda --- /dev/null +++ b/compat/src/test/scala/test/scala/collection/OptionTest.scala @@ -0,0 +1,48 @@ +/* + * Scala (https://www.scala-lang.org) + * + * Copyright EPFL and Lightbend, Inc. + * + * Licensed under Apache License 2.0 + * (http://www.apache.org/licenses/LICENSE-2.0). + * + * See the NOTICE file distributed with this work for + * additional information regarding copyright ownership. + */ + +package test.scala.collection + +import scala.collection.compat._ +import org.junit.Test +import org.junit.Assert._ + +class OptionTest { + + private val value: String = "example" + private val some: Option[String] = Some(value) + private val none: Option[String] = None + + @Test + def testWhenTrue: Unit = { + val option = Option.when(true)(value) + assertEquals(option, some) + } + + @Test + def testWhenFalse: Unit = { + val option = Option.when(false)(value) + assertEquals(option, none) + } + + @Test + def testUnlessTrue: Unit = { + val option = Option.unless(true)(value) + assertEquals(option, none) + } + + @Test + def testUnlessFalse: Unit = { + val option = Option.unless(false)(value) + assertEquals(option, some) + } +}