Last active
April 2, 2023 10:11
-
-
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/fc5f967a1b2df743a0dd2d2867d476c027d1f657
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.1.1" | |
// --------------------- | |
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