Compose Try Better

I want to have some utilities for using and clearing the resource, safe and unsafe, and clearing the resource after use, which is somewhat equivalent to try / finally, which allows me to clear even if the operation throws an exception.

I have

def withResource[R, U](create: => R, cleanup: R => Unit)(op: R => U): U = {
  val r = create
  val res = op(r)
  cleanup(r)
  res
}

def tryWithResource[R, U](create: => R, cleanup: R => Unit)(op: R => U): Try[U] = {
  val tried: (R => Try[U]) = (r: R) => Try.apply(op(r))
  withResource(create, cleanup)(tried)
}

but I do not like

val tried: (R => Try[U]) = (r: R) => Try.apply(op(r))

I seem to be missing some obvious compositional function, but I can't see where. I tried

val tried: (R => Try[U]) = (Try.apply _).compose(op)

but with typecheck error with

type mismatch;
[error]  found   : R => U
[error]  required: R => => Nothing
[error]     val tried: (R => Try[U]) = (Try.apply _).compose(op)

What am I missing / is something wrong?

+2
source share
2 answers

You can use a type type to restrict the parameter you pass from Try.applyto U:

val tried = (Try.apply(_: U)) compose op
+5
source

You can just use map

val tried: (R => Try[U]) = Try.apply(_).map(op)

http://www.scala-lang.org/files/archive/nightly/docs/library/index.html#scala.util.Try

+7

Source: https://habr.com/ru/post/1610415/


All Articles