Skip to content

Commit 92c0bb9

Browse files
committed
Specialised Option.tapEach to preserve the type
1 parent 9da742f commit 92c0bb9

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/main/scala/scala/collection/next/package.scala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,15 @@ package object next {
1919
col: IterableOnceOps[A, CC, C]
2020
): NextIterableOnceOpsExtensions[A, CC, C] =
2121
new NextIterableOnceOpsExtensions(col)
22+
23+
implicit final class OptionOpsExtensions[A](val v: Option[A]) extends AnyVal {
24+
/** Apply the side-effecting function $f to the option's value,
25+
* if it is nonempty. Otherwise, do nothing.
26+
*
27+
* @param f a function to apply to the option's value
28+
* @tparam B the return type of f
29+
* @return the option
30+
*/
31+
def tapEach[B](f: A => B): Option[A] = { v.foreach(f); v }
32+
}
2233
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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 scala.collection.next
14+
15+
import org.junit.Assert._
16+
import org.junit.Test
17+
18+
final class TestOptionOpsExtensions {
19+
// Compile checks the return type, no need to run as test.
20+
def tapEachReturnType(): Option[Int] = Option(5).tapEach(identity)
21+
}

0 commit comments

Comments
 (0)