Created
June 23, 2019 21:48
-
-
Save justinhj/33377034af264e9201c04388ba9f49cc to your computer and use it in GitHub Desktop.
StateT with Either for error handling
This file contains hidden or 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
| import cats._ | |
| import cats.implicits._ | |
| import cats.data.StateT | |
| object Radio { | |
| case class Radio(volume: Int) | |
| type RadioError = String | |
| type RadioEither[A] = Either[RadioError, A] | |
| type RadioStateEitherT[A] = StateT[RadioEither, Radio, A] | |
| def changeVolume(v: Int) = StateT[RadioEither, Radio, Int] { | |
| radioState => | |
| val newVolume = radioState.volume + v | |
| if(newVolume >= 0) | |
| Either.right((Radio(newVolume), newVolume)) | |
| else | |
| Either.left("User set negative volume") | |
| } | |
| def main(args: Array[String]): Unit = { | |
| val operateRadio = for ( | |
| volume <- changeVolume(10) | |
| ) yield volume | |
| println(operateRadio.run(Radio(10))) | |
| val badOperateRadio = for ( | |
| volume <- changeVolume(-20) | |
| ) yield volume | |
| println(badOperateRadio.run(Radio(10))) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment