Skip to content

Instantly share code, notes, and snippets.

@justinhj
Created June 23, 2019 21:48
Show Gist options
  • Select an option

  • Save justinhj/33377034af264e9201c04388ba9f49cc to your computer and use it in GitHub Desktop.

Select an option

Save justinhj/33377034af264e9201c04388ba9f49cc to your computer and use it in GitHub Desktop.
StateT with Either for error handling
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