Last active
August 11, 2018 17:47
-
-
Save agluszak/400b95f063dcd4b580b0bc1a277ba2f6 to your computer and use it in GitHub Desktop.
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
import cats.data.OptionT | |
import cats.implicits._ | |
import java.util.Date | |
object MonadTrans { | |
val person1 = Person(None, new Date()) | |
var person2 = Person(Some(person1), new Date()) | |
var person3 = Person(None, new Date()) | |
var person4 = Person(Some(person3), new Date()) | |
val persons: List[Person] = List(person1, person2, person3, person4) | |
def main(args: Array[String]): Unit = { | |
println(getBirthdays(persons)) | |
println(getBirthdaysMonadTransformer(persons)) | |
} | |
def getBirthdays(persons: List[Person]): List[Option[Date]] = { | |
val spouses: List[Option[Person]] = persons.map(_.marriedTo) | |
spouses.map(_.map(_.birthDay)) | |
} | |
def getBirthdaysMonadTransformer(persons: List[Person]): List[Option[Date]] = { | |
val spouses: List[Option[Person]] = persons.map(_.marriedTo) | |
val spousesT: OptionT[List, Person] = OptionT(spouses) | |
spousesT.map(_.birthDay).value | |
} | |
case class Person(marriedTo: Option[Person], birthDay: Date) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment