Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 25, 2024 10:20
Show Gist options
  • Save dacr/01b5cd0f3c447bb1a60c63280b4d3b9c to your computer and use it in GitHub Desktop.
Save dacr/01b5cd0f3c447bb1a60c63280b4d3b9c to your computer and use it in GitHub Desktop.
Using scala new chaining capabilities / published by https://github.com/dacr/code-examples-manager #a85f93f9-fc26-462b-84d5-ee2d2b322e9d/3d753ee111728727cf6ff4208e309c39d7d42677
// summary : Using scala new chaining capabilities
// keywords : scala, language-feature, chaining, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : a85f93f9-fc26-462b-84d5-ee2d2b322e9d
// created-on : 2020-11-07T08:29:43Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.4.2"
// ---------------------
import scala.util.{Failure, Random, Success, Try}
import scala.util.chaining._
def `Schrödinger's Cat`(id:Int): String =
if (Random.nextInt(2) == 1) throw new Exception(s"$id-poised") else s"$id-alive"
val experiment1 =
Try(`Schrödinger's Cat`(1))
.tap{case Success(_)=> case Failure(ex) => println(s"found dead : ${ex.getMessage} ")}
.toOption
.getOrElse("was dead")
def lookInside:PartialFunction[Try[String],Unit] = {
case Success(value) =>
case Failure(exception) => println(s"found dead : ${exception.getMessage} ")
}
val experiment2 =
Try(`Schrödinger's Cat`(2))
.tap(lookInside)
.toOption
.getOrElse("was dead")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment