├── .github └── workflows │ └── scala.yml ├── .gitignore ├── .scalafmt.conf ├── LICENSE ├── Readme.md ├── build.sbt ├── project ├── build.properties └── plugins.sbt ├── publish.sh └── src ├── main └── scala │ └── quest │ ├── QuestionOperatorSupport.scala │ └── ops.scala └── test └── scala ├── example └── HelloWorld.scala └── quest ├── PerformanceSpec.scala ├── QuestSpec.scala └── TestBase.scala /.github/workflows/scala.yml: -------------------------------------------------------------------------------- 1 | name: Scala CI 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | permissions: 10 | contents: read 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Set up JDK 11 20 | uses: actions/setup-java@v3 21 | with: 22 | java-version: '11' 23 | distribution: 'temurin' 24 | cache: 'sbt' 25 | - name: Run tests 26 | run: sbt test 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | .idea 3 | .bsp 4 | 5 | -------------------------------------------------------------------------------- /.scalafmt.conf: -------------------------------------------------------------------------------- 1 | version=3.5.9 2 | maxColumn = 120 3 | assumeStandardLibraryStripMargin = true 4 | newlines.beforeCurlyLambdaParams = never 5 | newlines.implicitParamListModifierPrefer = before 6 | comments.wrap = no 7 | align.preset = most 8 | runner.dialect=scala3 9 | docstrings.style = Asterisk -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Rust-like Question Operator for Scala 3 2 | 3 | This small library introduces a Rust-like `?`-Operator for Scala 3. 4 | 5 | ## Example 6 | 7 | 8 | ```scala 9 | // Add to build.sbt 10 | libraryDependencies += "net.reactivecore" %% "quest" % 11 | ``` 12 | 13 | ```scala 14 | import quest.* 15 | 16 | def getUser(id: Int): Option[String] = { ... } 17 | 18 | def getPermissions(id: Int): Option[List[String]] = { ... } 19 | 20 | def getUserAndPermissions(id: Int): Option[(String, List[String])] = quest { 21 | val user = getUser(id).? 22 | val permissions = getPermissions(id).? 23 | Some((user, permissions)) 24 | } 25 | ``` 26 | 27 | ## Operations 28 | 29 | - `quest(f: => T): T` initiates a block within which the question operator can be utilized. 30 | - `?` extracts the value from some type (e.g. `Either[L,R]`) if it represents a success, or exits the quest block if it represents a failure. 31 | - `bail(value: T)` immediately exits the quest block with the specified value. It's an alias for `scala.util.boundary.break`. 32 | 33 | ## Supported Types 34 | 35 | - `Option[T]` 36 | - `Either[L,R]` 37 | - `Try[T]` 38 | 39 | To use other types with the question operator, implement the `QuestionOperatorSupport` type class. 40 | 41 | ## How it works 42 | 43 | The quest block leverages `scala.util.boundary` which uses exceptions for early exit. In cases of failure, an `scala.util.boundary.Break` exception is thrown and caught by the `scala.boundary.apply` function. (Note that this is optimised to a labelled jump, instead of exception, when no intermediate closures are in between `?` and `quest`) 44 | 45 | 46 | Two helper classes simplify its use: 47 | 48 | - `scala.boundary.Label[T]` captures the return type of the `quest`/`break` method, enabling the question operator and leveraging Scala's type system to determine the correct return type 49 | - `QuestionOperatorSupport[T]` decodes each supported type into it's Failure and Success type. Failure and Success type 50 | can be gathered using the Aux-Pattern: `QuestionOperatorSupport.Aux[T,F,S]` 51 | 52 | ## Features 53 | 54 | - Short notation 55 | - Minimal codebase (50 LOC) 56 | - Compatible with IntelliJ IDEA (unlike some macros) 57 | - Supports Loom-based virtual threads 58 | 59 | ## Caveats 60 | 61 | - `scala.util.boundary` uses exceptions for control flow, deviating from purely functional Scala practices. This approach may cause issues in certain contexts: 62 | - It is incompatible with delayed execution contexts (e.g., `Future`, Effect Systems or collection views), potentially throwing `Break` exceptions unexpectedly. 63 | 64 | ## Performance 65 | 66 | - A small performance test measured an overhead of ~5ns per Failure return per Call in comparison to flatMap and return. 67 | 68 | ## Prior Art 69 | 70 | - Martin Ordersky: [Direct Style Scala (Scalar 2023)](https://www.youtube.com/watch?v=0Fm0y4K4YO8) 71 | - Built upon `scala.util.boundary` after Hint on Reddit 72 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | import xerial.sbt.Sonatype.GitHubHosting 2 | 3 | ThisBuild / scalaVersion := "3.3.1" 4 | 5 | ThisBuild / organization := "net.reactivecore" 6 | 7 | // If there is a Tag starting with v, e.g. v0.3.0 use it as the build artefact version (e.g. 0.3.0) 8 | val versionTag = sys.env 9 | .get("CI_COMMIT_TAG") 10 | .filter(_.startsWith("v")) 11 | .map(_.stripPrefix("v")) 12 | 13 | val snapshotVersion = "0.2-SNAPSHOT" 14 | val artefactVersion = versionTag.getOrElse(snapshotVersion) 15 | ThisBuild / version := artefactVersion 16 | 17 | 18 | def publishSettings = Seq( 19 | publishTo := sonatypePublishToBundle.value, 20 | sonatypeBundleDirectory := (ThisBuild / baseDirectory).value / "target" / "sonatype-staging" / s"${version.value}", 21 | licenses := Seq("APL2" -> url("http://www.apache.org/licenses/LICENSE-2.0.txt")), 22 | homepage := Some(url("https://github.com/reactivecore/quest")), 23 | sonatypeProjectHosting := Some(GitHubHosting("reactivecore", "quest", "contact@reactivecore.de")), 24 | developers := List( 25 | Developer( 26 | id = "nob13", 27 | name = "Norbert Schultz", 28 | email = "norbert.schultz@reactivecore.de", 29 | url = url("https://www.reactivecore.de") 30 | ) 31 | ), 32 | publish / test := {}, 33 | publishLocal / test := {} 34 | ) 35 | 36 | usePgpKeyHex("77D0E9E04837F8CBBCD56429897A43978251C225") 37 | 38 | 39 | val ScalaTestVersion = "3.2.17" 40 | 41 | lazy val testSettings = libraryDependencies ++= Seq( 42 | "org.scalatest" %% "scalatest" % ScalaTestVersion % "test", 43 | "org.scalatest" %% "scalatest-flatspec" % ScalaTestVersion % "test" 44 | ) 45 | 46 | 47 | lazy val root = (project in file(".")) 48 | .settings( 49 | name := "quest", 50 | testSettings, 51 | publishSettings 52 | ) 53 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version = 1.9.8 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("com.timushev.sbt" % "sbt-updates" % "0.6.3") 2 | addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.21") 3 | addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2") 4 | -------------------------------------------------------------------------------- /publish.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | export CI_COMMIT_TAG=`git describe --tags` 4 | echo "Publishing for $CI_COMMIT_TAG" 5 | source ~/bin/java11.sh 6 | 7 | read -p "Press enter to continue" 8 | 9 | sbt publishSigned sonatypeBundleRelease 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/main/scala/quest/QuestionOperatorSupport.scala: -------------------------------------------------------------------------------- 1 | package quest 2 | 3 | import scala.annotation.implicitNotFound 4 | import scala.util.{Failure, Try} 5 | 6 | /** Helper trait for implementing the Question-Operator syntax for different types. */ 7 | @implicitNotFound("Could not find QuestionOperatorSupport for ${T}") 8 | trait QuestionOperatorSupport[-T] { 9 | 10 | /** Success type. */ 11 | type Success 12 | 13 | /** Failure Type. */ 14 | type Failure 15 | 16 | /** Split some result into success or failure. */ 17 | def decode[X <: T](value: X): Either[Failure, Success] 18 | } 19 | 20 | object QuestionOperatorSupport { 21 | type Aux[T, F, S] = QuestionOperatorSupport[T] { 22 | type Failure = F 23 | type Success = S 24 | } 25 | 26 | given forEither[L, R]: QuestionOperatorSupport.Aux[Either[L, R], Left[L, Nothing], R] = 27 | new QuestionOperatorSupport[Either[L, R]] { 28 | override type Failure = Left[L, Nothing] 29 | override type Success = R 30 | 31 | override def decode[X <: Either[L, R]](value: X): Either[Left[L, Nothing], R] = { 32 | value match { 33 | case Left(l) => Left(Left(l)) 34 | case Right(r) => Right(r) 35 | } 36 | } 37 | } 38 | 39 | given forOption[T]: QuestionOperatorSupport.Aux[Option[T], None.type, T] = { 40 | new QuestionOperatorSupport[Option[T]] { 41 | override type Failure = None.type 42 | override type Success = T 43 | 44 | override def decode[X <: Option[T]](value: X): Either[None.type, T] = { 45 | value.toRight(None) 46 | } 47 | } 48 | } 49 | 50 | given forTry[T]: QuestionOperatorSupport.Aux[Try[T], Failure[Nothing], T] = { 51 | new QuestionOperatorSupport[Try[T]] { 52 | override type Failure = scala.util.Failure[Nothing] 53 | override type Success = T 54 | 55 | override def decode[X <: Try[T]](value: X): Either[Failure, T] = { 56 | value.toEither.left.map(Failure.apply) 57 | } 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/scala/quest/ops.scala: -------------------------------------------------------------------------------- 1 | package quest 2 | 3 | import scala.util.boundary.{Label, break} 4 | import scala.util.boundary 5 | 6 | /** 7 | * Start a quest block. Inside the block, the question operator can be used. 8 | * 9 | * Note: this wraps [[scala.util.boundary.apply]]. 10 | */ 11 | inline def quest[T](f: Label[T] ?=> T): T = { 12 | boundary { 13 | f 14 | } 15 | } 16 | 17 | extension [T](in: T) { 18 | 19 | /** 20 | * Return the success value or return the quest-block with the error value. 21 | * 22 | * Must be used inside a quest block 23 | */ 24 | inline def ?[F, S](using support: QuestionOperatorSupport.Aux[T, F, S], label: Label[F]): S = { 25 | support.decode(in) match { 26 | case Left(bad: F) => break(bad) 27 | case Right(ok) => ok 28 | } 29 | } 30 | } 31 | 32 | /** 33 | * Immediately return the [[quest]] method returning value. 34 | * 35 | * You can also use `return`, but this doesn't always works in closures. 36 | * 37 | * Must be used inside a quest block 38 | * 39 | * Note: this wraps [[scala.util.boundary.break]] 40 | */ 41 | inline def bail[T: Label](value: T): Nothing = { 42 | break(value) 43 | } 44 | -------------------------------------------------------------------------------- /src/test/scala/example/HelloWorld.scala: -------------------------------------------------------------------------------- 1 | package example 2 | import quest.* 3 | 4 | def getUser(id: Int): Option[String] = { 5 | id match { 6 | case 10 => Some("Alice") 7 | case 11 => Some("Bob") 8 | case _ => None 9 | } 10 | } 11 | 12 | def getPermissions(id: Int): Option[List[String]] = { 13 | id match { 14 | case 10 => Some(List("Admin")) 15 | case _ => None 16 | } 17 | } 18 | 19 | def getUserAndPermissions(id: Int): Option[(String, List[String])] = quest { 20 | val user = getUser(id).? 21 | val permissions = getPermissions(id).? 22 | Some((user, permissions)) 23 | } 24 | 25 | object HelloWorld extends App { 26 | 27 | println(getUserAndPermissions(10)) 28 | println(getUserAndPermissions(11)) 29 | println(getUserAndPermissions(12)) 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/test/scala/quest/PerformanceSpec.scala: -------------------------------------------------------------------------------- 1 | package quest 2 | 3 | class PerformanceSpec extends TestBase { 4 | 5 | def sucMod(in: Int, mod: Int): Option[Int] = { 6 | val cand = in + 1 7 | if (cand >= mod) { 8 | None 9 | } else { 10 | Some(cand) 11 | } 12 | } 13 | 14 | /* 15 | Test method: Three different methods which increment a number by three, but not if it leaves it's modulo range. 16 | The function is called with a lot of numbers and smaller mod, so it ensures that a lot of error returns are created. 17 | It should measure the overhead of the exception throwing inside quest. 18 | */ 19 | 20 | def withFlatMap(in: Int, mod: Int): Option[Int] = { 21 | for { 22 | a <- sucMod(in, mod) 23 | b <- sucMod(a, mod) 24 | c <- sucMod(b, mod) 25 | } yield { 26 | c 27 | } 28 | } 29 | 30 | def withReturnAndPatternMatch(in: Int, mod: Int): Option[Int] = { 31 | val a = sucMod(in, mod) match { 32 | case None => return None 33 | case Some(a) => a 34 | } 35 | val b = sucMod(a, mod) match { 36 | case None => return None 37 | case Some(b) => b 38 | } 39 | sucMod(b, mod) 40 | } 41 | 42 | def withQuest(in: Int, mod: Int): Option[Int] = quest { 43 | val a = sucMod(in, mod).? 44 | val b = sucMod(a, mod).? 45 | sucMod(b, mod) 46 | } 47 | 48 | inline def testIterations(size: Int, mod: Int, inline f: (Int, Int) => Option[Int], message: String): Unit = { 49 | val it = (0 until size).iterator 50 | val t0 = System.nanoTime() 51 | while (it.hasNext) { 52 | val i = it.next() 53 | val result = f(i, mod) 54 | if (i < mod - 3) { 55 | result shouldBe Some(i + 3) 56 | } else { 57 | result shouldBe None 58 | } 59 | } 60 | val t1 = System.nanoTime() 61 | println( 62 | s"${message}, iterations=${size}, mod=${mod} dt=${(t1 - t0).toDouble / 1_000_000_000}s, per call=${(t1 - t0).toDouble / size}ns" 63 | ) 64 | } 65 | 66 | def testAll(size: Int, mod: Int): Unit = { 67 | s"size ${size}" should "work" in { 68 | for (round <- 0 until 10) { 69 | println(s"Round: ${round}") 70 | testIterations(size, mod, withFlatMap, "withFlatMap") 71 | testIterations(size, mod, withReturnAndPatternMatch, "withReturnAndPatternMatch") 72 | testIterations(size, mod, withQuest, "withQuest") 73 | } 74 | } 75 | } 76 | 77 | testAll(10, 3) 78 | testAll(1000, 300) 79 | testAll(100000, 30000) 80 | testAll(10000000, 3000000) // More than 7 Million exceptions 81 | } 82 | -------------------------------------------------------------------------------- /src/test/scala/quest/QuestSpec.scala: -------------------------------------------------------------------------------- 1 | package quest 2 | 3 | import scala.util.{Failure, Success, Try} 4 | import scala.util.boundary.break 5 | 6 | class QuestSpec extends TestBase { 7 | 8 | it should "work in a simple case" in { 9 | val a: Option[Int] = Some(3) 10 | val b: Option[Int] = None 11 | 12 | quest { 13 | Some(a.? + b.?) 14 | } shouldBe None 15 | } 16 | 17 | it should "support either" in { 18 | val a: Either[String, Int] = Right(23) 19 | val b: Either[String, Boolean] = Left("Bad") 20 | 21 | quest { 22 | val x = a.? 23 | val y = b.? 24 | } shouldBe Left("Bad") 25 | } 26 | 27 | it should "support either (success case with diverging error codes)" in { 28 | val a: Either[String, Int] = Right(23) 29 | val b: Either[String, Boolean] = Right(true) 30 | 31 | val res = quest { 32 | val x = a.? 33 | val y = b.? 34 | val z = if (y) x else -1 35 | Right(z) 36 | } 37 | res shouldBe Right(23) 38 | } 39 | 40 | it should "support try" in { 41 | val a: Try[Int] = Success(10) 42 | val b: Try[Int] = Success(32) 43 | 44 | val rt = new RuntimeException("BOOM") 45 | val c: Try[Int] = Failure(rt) 46 | 47 | val res = quest { 48 | Success(a.? + b.?) 49 | } shouldBe Success(42) 50 | 51 | val res2 = quest { 52 | Success(a.? + c.?) 53 | } shouldBe Failure(rt) 54 | } 55 | 56 | it should "support bailing" in { 57 | val x: Option[Int] = quest { 58 | bail(None) 59 | Some(5) 60 | } 61 | x shouldBe None 62 | 63 | val y: Option[Int] = quest { 64 | bail(Some(3)) 65 | None 66 | } 67 | y shouldBe Some(3) 68 | } 69 | 70 | // Testing custom types 71 | 72 | sealed trait Base 73 | case class Err(msg: String) extends Base 74 | case class Ok(value: Int) extends Base 75 | 76 | given support: QuestionOperatorSupport.Aux[Base, Err, Int] = new QuestionOperatorSupport[Base] { 77 | override type Failure = Err 78 | override type Success = Int 79 | 80 | override def decode[X <: Base](value: X): Either[Err, Int] = { 81 | value match { 82 | case e: Err => Left(e) 83 | case ok: Ok => Right(ok.value) 84 | } 85 | } 86 | } 87 | 88 | it should "support custom types" in { 89 | val x = quest { 90 | Ok(123).? 91 | Ok(235).? 92 | Ok(400) 93 | } 94 | x shouldBe Ok(400) 95 | 96 | val y = quest { 97 | Ok(123).? 98 | Err("boom").? 99 | Ok(400).? 100 | } 101 | y shouldBe Err("boom") 102 | } 103 | 104 | it should "handle correct return type" in { 105 | val x = quest { 106 | bail(Err("Boom!")) 107 | Ok(42) 108 | } 109 | 110 | x shouldBe Err("Boom!") 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/test/scala/quest/TestBase.scala: -------------------------------------------------------------------------------- 1 | package quest 2 | 3 | import org.scalatest.BeforeAndAfterEach 4 | import org.scalatest.flatspec.AnyFlatSpec 5 | import org.scalatest.matchers.should.Matchers 6 | 7 | abstract class TestBase extends AnyFlatSpec with Matchers with BeforeAndAfterEach {} 8 | --------------------------------------------------------------------------------