Created
October 31, 2017 14:12
-
-
Save franklinchou/394c090b6033cc80ee7ed5a07713c856 to your computer and use it in GitHub Desktop.
Getting try/catch to work in Scala
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 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