Skip to content

Commit

Permalink
Merge pull request #541 from pedorich-n/option-companion-object-methods
Browse files Browse the repository at this point in the history
Option.when and Option.unless added
  • Loading branch information
lrytz authored Jul 7, 2022
2 parents 7a1171d + ed5116d commit 3dcd0ae
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
48 changes: 48 additions & 0 deletions compat/src/test/scala/test/scala/collection/OptionTest.scala
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit 3dcd0ae

Please sign in to comment.