mslinn / scalacourses-utils

Scala Future enhancements, memoization and more

GitHub

ScalaCourses Scala Utils

License Build Status Download

Installation

Add this resolver:

"micronautics/scala on bintray" at "http://dl.bintray.com/micronautics/scala"

Add this dependency:

"com.micronautics" %% "scalacourses-utils" % "0.2.21" withSources()

Usage

For enriched Try:

import com.micronautics.utils.Implicits._

val x: Try[Int] = Try {
	2 / 0
} andThen {
	case Failure(ex) => println(s"Logging ${ex.getMessage}")
} andThen {
	case Success(value) => println(s"Success: got $value")
	case Failure(ex) => println(s"This just shows that any failure is provided to each chained andThen clause ${ex.getMessage}")
}

For working with collections of Try:

import com.micronautics.utils.Implicits._

val tries = List(Try(6/0), Try("Happiness " * 3), Failure(new Exception("Drat!")), Try(99))

println(s"failures=${failures(tries).map(_.getMessage).mkString("; ")}")
println(s"successes=${successes(tries)}")
println(s"sequence=${sequence(tries)}")
val (successes, failures) = sequenceWithFailures(tries)
println(s"""sequenceWithFailures:
	successes=$successes
	failures=$failures""")

For working with caches:

import com.google.common.cache.CacheStats
import com.micronautics.cache._
import scala.concurrent.ExecutionContext.Implicits._

val softCache = SoftCache[String, Int]()
val x: Option[Int] = softCache.get("missing")
val y: Int = softCache.getWithDefault("2", 2))
cache.put("3", 3)
cache.remove("3")
val stats: CacheStats = cache.underlying.stats

val strongCache = StrongCache[String, String]()
val x: Option[String] = softCache.get("missing")
val y: String = softCache.getWithDefault("2", "two"))
cache.put("3", "three")

See Also

The ScalaCourses Intermediate Scala Course has several lectures on Scala Futures, and a full discussion of the contents of this library is provided in the Working With Collections of Futures lecture. The Partial Functions lecture discusses the RichTry class and methods for working with collections of Try.

The course also provides a working SBT project that demonstrates this code.

The same course has a lecture on Memoization in Depth which discusses the memoization code in detail.

Scaladoc

Here