A very common use case when dealing with options...
val values = List(Some("a"), None, Some("b")).flatten| import cats._ | |
| import cats.implicits._ | |
| def loadResult[F[_]](implicit F: MonadError[F, Throwable]): F[String] = { | |
| val resultEitherF: F[Either[Throwable, String]] = ??? | |
| val resultF: F[String] = resultEitherF.flatMap(F.fromEither) | |
| resultF.recoverWith{ | |
| case error => F.pure(error.getMessage) | |
| } | |
| } |
| //typeclass example | |
| //Note : List already has a sum method working the same way | |
| //List(1,2,3).sum returns 6 | |
| //but this example is simpler | |
| // Monoid = summable + neutral element | |
| trait Monoid[T] { | |
| def combine(a: T, b: T): T | |
| def empty: T |
| //example with Generic trait | |
| trait Summable[T] { | |
| def sumWith(other: T): T | |
| } | |
| implicit class StringSummable(s: String) extends Summable[String]{ | |
| def sumWith(other: String): String = s + other | |
| } |
| interface HasScore { | |
| score: number; | |
| // also works with functions instead of properties | |
| } | |
| let player = { score: 0 }; | |
| function addPointsToScore(player: HasScore, points: number): void { | |
| player.score += points; | |
| } |
| @Test | |
| fun combineNullable() { | |
| fun giveInt(x: Int):Int? = x+1 | |
| fun giveInt2(x: Int):Int? = x+2 | |
| fun combine(x: Int): Int? = giveInt(x)?.let { giveInt2(it) } | |
| assertEquals(combine(1),4) | |
| } |
| class Application @Inject() (implicit actorSystem: ActorSystem, exec: ExecutionContext) extends Controller { | |
| implicit val materializer = ActorMaterializer() | |
| val Tick = "tick" | |
| class TickActor(queue: SourceQueue[String]) extends Actor { | |
| def receive = { | |
| case Tick => queue.offer("tack") | |
| } |
| var names = ['joe', 'bob']; | |
| Object.observe(names, function(changes){ | |
| changes.forEach(function(change) { | |
| console.log(change.type, change.name) | |
| }); | |
| console.log("names",names); | |
| }); | |
| class PrintService { | |
| def print = println("I'm a real service") | |
| } | |
| trait Services { | |
| val printService = new PrintService() | |
| // put your other services here | |
| } | |
| //for example, a Play controller |
| val f: Future[Int] = Future { | |
| if(math.random < 0.5) 1 else throw new Exception("Oh no") | |
| } recover { | |
| case ex:Exception => { | |
| println(ex.getMessage) | |
| -1 | |
| } | |
| } | |
| f map println |