Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Option.when and Option.unless added #541

Merged
merged 4 commits into from
Jul 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}