Skip to content

Commit 17cea9d

Browse files
authored
Merge pull request #80 from gdiet/topic/Option-specialized-tapEach
Specialised Option.tapEach to preserve the type
2 parents 737c726 + 0eefc7b commit 17cea9d

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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
14+
15+
package object next {
16+
implicit final class OptionOpsExtensions[A](private val v: Option[A]) extends AnyVal {
17+
/** Apply the side-effecting function `f` to the option's value
18+
* if it is nonempty. Otherwise, do nothing.
19+
*
20+
* @param f a function to apply to the option's value
21+
* @return the option
22+
*/
23+
def tapEach[B](f: A => B): Option[A] = { v.foreach(f); v }
24+
}
25+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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.test
14+
15+
import scala.next._
16+
17+
final class TestOptionOpsExtensions {
18+
// Compile checks the return type, no need to run as test.
19+
def tapEachReturnType(): Option[Int] = {
20+
// Don't return the option directly, so the compiler is not able to coerce a specific implicit to be used.
21+
val opt = Option(5).tapEach(identity)
22+
opt.map(identity)
23+
}
24+
}

0 commit comments

Comments
 (0)