Skip to content

Instantly share code, notes, and snippets.

@franklinchou
Created October 31, 2017 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save franklinchou/394c090b6033cc80ee7ed5a07713c856 to your computer and use it in GitHub Desktop.
Save franklinchou/394c090b6033cc80ee7ed5a07713c856 to your computer and use it in GitHub Desktop.
Getting try/catch to work in Scala
import java.time.LocalDate
import java.time.TemporalAdjusters
import scala.util.{Success, Failure, Try}
import org.scalatest.FunSpec
/**
* Check if date passed is the last day of the month.
*/
object Check {
def endDateCheck(d: LocalDate): Try[String] = {
val lastDay = d.`with`(d.getMonth).`with`(TemporalAdjusters.lastDayOfMonth)
val error: String = "Warning! Date passed is not last day of month."
if (d == lastDay) Success("")
else Failure(new Exception(error))
}
}
object Main {
def evaluate(d: LocalDate): Try[String] = {
Try(Check.endDateCheck(d)) match {
case Failure(fail) => Failure(fail)
case Success(_) => Success("")
}
}
}
class CheckSpec exends FunSpec {
describe("Try/Catch example") {
it("should return a value") {
Main.evaluate(LocalDate.of(2017, 10, 31)) match {
case Failure(error) => println(error)
case Success(result) => assert(result.isEmpty)
}
}
it ("should return an error") {
Main.evaluate(LocalDate.of(2017, 10, 1)) match {
case Failure(error) => assert(error.getMessage == "Warning! Date passed is not last day of month.")
case Success(result) => println(result)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment