I'm trying to change a method into a function, but I'm having troubles with the return type:
sealed trait CronJobStatus
case object CronJobSuccess extends CronJobStatus
case class CronJobFailure(error: Option[String] = None) extends CronJobStatus
My method (which works) is:
def jobNotFoundFailure(name: String): CronJobStatus = CronJobFailure(Some(s"Job with name $name not found"))
When trying to have jobNotFoundFailure as a function, I'm unable to find the right syntax to specify that it returns a CronJobStatus, I've got this function (but it returns CronJobFailure)
val jobNotFoundFailure = (name: String) => CronJobFailure(Some(s"Job with name $name not found"))
Which means I can't use this function where a CronJobStatus is expected. eg when getting an Opt from a map and folding:
cronJobsMap.get(name).fold(jobNotFoundFailure(name))(doDelete)
Another possible option is:
val jobNotFoundFailure = (name: String) =>
CronJobFailure(Some(s"Job with name $name not found")): CronJobStatus
By the way your code (ignoring the fact that I don't know how doDelete
looks like) seems to work even if jobNotFoundFailure is String => CronJobFailure
.
cronJobsMap.get(name).fold(jobNotFoundFailure(name))(doDelete)
Whenever CronJobStatus
is needed you can put CronJobFailure
. Wherever function A => CronJobStatus
is needed A => CronJobFailure
is also valid because Function1[-T, +R]
is covariant in the type of returned value.
You can write
val jobNotFoundFailure: String => CronJobStatus =
name => CronJobFailure(Some(s"Job with name $name not found"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.