Future that cannot fail in Scala - scala

Is there the concept of a Future that cannot fail in Scala?
I'm transforming a Future[Result], which may fail—therefore I handle both a Failure and a Success—into a Future[Option[String]], carrying an optional error message derived from the failure or success states. So far, so good.
Thing is now, I would like to formally (i.e., with the help of the type system) remember that this future will always hold a Success and that I won't need to handle the failure case in the future.
Is there a smart way to do this?

You cannot do that "with the help of type system" because there is no way for the type system to guarantee a Future will not fail, even if you promise that it won't.
Consider this:
Future { doStuff(); }
.recover { case _ => "Failed!" } // Now it always succeeds
.map { _ => Seq.empty[String].head } // Now it does not.
Even if you were going to make any further transformations impossible, once the Future has been declared to always succeed, that still does not help, because the exception handler (or whatever you do to convert the original future to the "always succeeding one") could throw.
Update: as pointed out in a comment below, the code snippet above is incorrect: the result of .map is not the same Future as the result of .recover. The point stands however. Here is the correct illustration:
Future { doStuff }
.recover { case _ => Seq.empty[String].head }

Isn't this what type-tagging is for?
scala> type Tagged[U] = { type Tag = U }
defined type alias Tagged
scala> type ##[T, U] = T with Tagged[U]
defined type alias $at$at
scala> trait OK ; trait Uncertain
defined trait OK
defined trait Uncertain
scala> type Sure[A] = Future[A] ## OK
defined type alias Sure
scala> type Unsure[A] = Future[A] ## Uncertain
defined type alias Unsure
scala> val f = Future.successful(42).asInstanceOf[Sure[Int]]
f: Sure[Int] = Future(Success(42))
then
scala> object X { def p(f: Sure[_]) = "sure" ; def p(f: Unsure[_])(implicit d: DummyImplicit) = "unsure" }
defined object X
scala> X.p(f)
res1: String = sure
It doesn't remain sure under map, of course.

Related

Why does creating a map function whose parameter is of type `Nothing => U` appear to work?

I'm writing Scala code that uses an API where calls to the API can either succeed, fail, or return an exception. I'm trying to make an ApiCallResult monad to represent this, and I'm trying to make use of the Nothing type so that the failure and exception cases can be treated as a subtype of any ApiCallResult type, similar to None or Nil. What I have so far appears to work, but my use of Nothing in the map and flatMap functions has me confused. Here's a simplified example of what I have with just the map implementation:
sealed trait ApiCallResult[+T] {
def map[U]( f: T => U ): ApiCallResult[U]
}
case class ResponseException(exception: APICallExceptionReturn) extends ApiCallResult[Nothing] {
override def map[U]( f: Nothing => U ) = this
}
case object ResponseFailure extends ApiCallResult[Nothing] {
override def map[U]( f: Nothing => U ) = ResponseFailure
}
case class ResponseSuccess[T](payload: T) extends ApiCallResult[T] {
override def map[U]( f: T => U ) = ResponseSuccess( f(payload) )
}
val s: ApiCallResult[String] = ResponseSuccess("foo")
s.map( _.size ) // evaluates to ResponseSuccess(3)
val t: ApiCallResult[String] = ResponseFailure
t.map( _.size ) // evaluates to ResponseFailure
So it appears to work the way I intended with map operating on successful results but passing failures and exceptions along unchanged. However using Nothing as the type of an input parameter makes no sense to me since there is no instance of the Nothing type. The _.size function in the example has type String => Int, how can that be safely passed to something that expects Nothing => U? What's really going on here?
I also notice that the Scala standard library avoids this issue when implementing None by letting it inherit the map function from Option. This only furthers my sense that I'm somehow doing something horribly wrong.
Three things are aligning to make this happen, all having to do with covariance and contravariance in the face of a bottom type:
Nothing is the bottom type for all types, e.g. every type is its super.
The type signature of Function1[-T, +R], meaning it accepts any type which is a super of T and returns any type for which R is a super.
The type ApiCallResult[+R] means any type U for which R is a super of U is valid.
So any type is a super of Nothing means both any argument type is valid and the fact that you return something typed around Nothing is a valid return type.
I suggest that you don't need to distinguish failures and exceptions most of the time.
type ApiCallResult[+T] = Try[T]
case class ApiFailure() extends Throwable
val s: ApiCallResult[String] = Success("this is a string")
s.map(_.size)
val t: ApiCallResult[String] = Failure(new ApiFailure)
t.map(_.size)
To pick up the failure, use a match to select the result:
t match {
case Success(s) =>
case Failure(af: ApiFailure) =>
case Failure(x) =>
}

Why is no implicit view found, when eta conversion and specifying type parameters does allow an implicit view to be found?

The code:
object Test {
import scala.language.implicitConversions
case class C1() {}
case class C2() {}
implicit def c1ToC2(in: C1): C2 = C2()
def from[A, B](in: A)(implicit f: A => B): B = f(in)
def fails(): Future[C2] = {
val future: Future[C1] = Future.successful(C1())
future.map(from) // this line fails to compile!
}
def compiles1(): Future[C2] = {
val future: Future[C1] = Future.successful(C1())
future.map(x => from(x))
}
def compiles2(): Future[C2] = {
val future: Future[C1] = Future.successful(C1())
future.map(from[C1, C2])
}
}
In this example, only the fails method fails to compile. The error message is:
Error:(23, 16) No implicit view available from A => B.
future.map(from)
I'm confused about why no implicit view is found. Based on the compiles1 and compiles2 methods, which both successfully compile, it seems there is an implicit view available from A => B.
What is going on here, and why do the two compilesN methods work, but fails does not?
My background: I'm still learning Scala, so it could easily be the case that I'm missing something pretty obvious. :)
I'm on Scala 2.11.8.
The compiler attempts to resolve implicits before eta-expansion of from into a function, so the type parameters of from are not yet inferred when you call it like this:
future.map(from)
compiles2 obviously works because you supply the type parameters on your own. When you call future.map(from[C1, C2]), the compiler knows it will need an implicit C1 => C2, because that's what you've told it.
With compiles1, the difference is a little more subtle, but it stems from the fact that future.map(from) and future.map(x => from(x)) are actually very different things. The former uses eta-expansion, which fails for the aforementioned reasons. With future.map(x => from(x)), there is no eta-expansion happening. Instead, you have an anonymous function that simply calls from instead of eta-expanding it. Therefore, the compiler can infer the type of x, which tells us that x is a C1 (in this case), and it can find the implicit conversion c1ToC2 that satisfies the type parameters of from while resolving the implicit and the final return type of the method, Future[C2].

Currying a generic method / function without loosing generic parameters

I just realized that my generic method:
def method[A](list: List[A]): A = { ... }
will result in a non-generic function type
val methodFun = method _
-> methodFun : (scala.List[Nothing]) => Nothing
when currying it, instead of keeping its generic type. Is there a possibility to keep the generic type information? I found out that I can define some explicit type as for example String by setting
val methodFun = method[String] _
-> methodFun : (scala.List[String]) => String
but this is not really what I want. I currently tend to use raw types to avoid this problems (as soon as I find out how) or is there a better solution?
Thanks for help!
PS: For why I want to do it:
def method1[A](list: List[A]): A = { ... }
def method2[A](element: A): Int = { ... }
// This will not cause a compiler error as stated before
// but this will result in (List[Nothing]) => Int
// but I want a (List[A]) => Int
val composedFun = method1 _ andThen method2
// The next line is possible
// but it gives me a (List[String]) => Int
val composedFunNonGeneric = method1[String] _ andThen method2[String]
Let's look at your example:
def method1[A](list: List[A]): A = { ... }
def method2[A](element: A): String = { ... }
// The next line will cause a compiler error
val composed = method1 _ andThen method2
First, that doesn't give me a compiler error, but rather has the too-specific type (List[Nothing]=>String) that you mentioned.
If you want to understand why this doesn't work, think about it this way: what is the type you're expecting for composed? I think you want something like this List[A]=>String. However, composed is a val, not a def (i.e. it's an instance of a function object, not a method). Object instances must have specific types. If you wanted to use a generic type here, then you'd have to wrap this val in a class definition with a generic type, but even then the generic type would be restricted to the type specified/inferred for each specific instance of that class.
In short, if you want to compose methods and keep the type parameter, you need to compose them manually and declare it with def instead:
def composed[A](list: List[A]): String = method2(method1(list))

How can I cast an object as parameter of Function1[Array[_], Unit] inScala

class MyClass(functions: Seq[Function1[Array[_], Unit]) {
def foo(parametersForEachFunction: Seq[Array[_]]) {
assert(functions.size == parametersForEachFunction.size)
for ((function, parameter) <- functions zip parametersForEachFunction) {
// Assume each parameter is suitable for the funcition
// What type parameter I should wrote in asInstanceOf?
function(parameter.asInstanceOf[ ?????? ])
}
}
}
I know an asInstanceOf is required here, but I don't know what type parameter I should wrote in asInstanceOf.
If you have to cast, you are doing it wrong. Whenever you think you should cast something, rollback and try something else. There are exceptions -- if the documentation of something explicitly tell you to cast, well, you have to cast. But don't count on you have such an exception: you probably don't.
As in this case.
scala> class MyClass(functions: Seq[Function1[Array[_], Unit]]) {
| def foo(parametersForEachFunction: Seq[Array[_]]) {
| assert(functions.size == parametersForEachFunction.size)
| for ((function, parameter) <- functions zip parametersForEachFunction) {
| function(parameter)
| }
| }
| }
defined class MyClass
Function0 takes only one type param, so not sure what you're doing.
If you're thinking about passing arbitrary argument to arbitrary arity of functions, you probably could look into Function2 etc's curried method or Function object's tupled. I vaguely recall scalaz being able to do this kind of stuff out of the box, but not sure.
You probably want Function1, since you want to pass one parameter. Function0, as the name implies, takes zero parameters. I prefer using A => B to Function1[A,B], so I'll write it that way. (Note that all functions have one return value.)
class MyClass(fns: Seq[Array[_] => Unit]) {
def foo(parms: Seq[Array[_]]) {
for ((f,p) <- fns zip parms) {
f(p)
}
}
}
Also, Array and only Array is non-generic. You can't pass an Array[Int] or an Array[String] in for an Array[_]. So the above probably doesn't do what you want:
scala> new MyClass(Seq((a: Array[_]) => println(a.length)))
res0: MyClass = MyClass#3fee3c8d
scala> new MyClass(Seq((a: Array[String]) => println(a.mkString)))
<console>:9: error: type mismatch;
found : Array[String] => Unit
required: Array[_] => Unit
new MyClass(Seq((a: Array[String]) => println(a.mkString)))
scala> new MyClass(Seq(((a: Array[String]) => println(a.mkString)).asInstanceOf[Array[_]=>Unit]))
res4: MyClass = MyClass#4b9cee52
scala> new MyClass(Seq(((a: Array[Int]) => println(a.sum)).asInstanceOf[Array[_]=>Unit]))
res5: MyClass = MyClass#2357f593
scala> res5.foo(Seq(Array(1,2,3).asInstanceOf[Array[_]]))
6
Ugh! Maybe you can find another way to represent what you want? (Since I don't know your use case, I hesitate to recommend anything.)

Choice of implicit conversion location with a block

In the following code, the implicit conversion is applied around the println(2) line; I had foolishly expected it to apply around the entire block { println(1); println(2) }. How should I reason about where the compiler places the implicit?
object Executor {
private var runnable: Runnable = _
def setRunnable(runnable: Runnable) {
this.runnable = runnable
}
def execute() { runnable.run() }
}
object Run extends App {
implicit def blockToRunnable(p: ⇒ Any): Runnable =
new Runnable { def run() = p }
Executor.setRunnable {
println(1)
println(2)
}
println("Before execute")
Executor.execute()
}
I rationalize this behavior like this: according to the spec, the type of a block {s1; s2; ...; sn; e } is the type of the last expression e.
So the compiler takes e and type checks it against Runnable. That fails, so it searches for an implicit conversion that will convert e to Runnable. So it would like this:
{ s1; s2; ... sn; convert(e) }
This is confirmed with scala -Xprint:typer on this small example:
class A
implicit def convert(a: A): String = a.toString
def f(s: String) { println(s) }
f{ println(1); new A }
prints:
private[this] val res0: Unit = $line3.$read.$iw.$iw.f({
scala.this.Predef.println(1);
$line2.$read.$iw.$iw.convert(new $line1.$read.$iw.$iw.A())
});
According to the spec, an implicit conversion is applied when the type of an expression does not match the expected type. The key observation is how the expected type is threaded when typing blocks.
if an expression e is of type T, and T does not conform to the expression’s expected type pt. In this case an implicit v is searched which is applicable to e and whose result type conforms to pt.
In Section 6.11 Blocks, the expected type of a block's last expression is defined as
The expected type of the final expression e is the expected type of the block.
Given this spec, it seems the compiler has to behave this way. The expected type of the block is Runnable, and the expected type of println(2) becomes Runnable as well.
A suggestion: if you want to know what implicits are applied, you can use a nightly build for 2.1 of the Scala IDE for Eclipse. It can 'highlight implicits'.
Edited: I admit it is surprising when there's a call-by-name implicit in scope.
The problem is that you are thinking of blocks as if they were thunks, as if they were pieces of code. They aren't. { a; b; c } is not a piece of code that can be passed around.
So, how should you reason about implicits? Actually, how should you reason about views, which are implicit conversions. Views are applied to the value that needs to be changed. In your example, the value of
{
println(1)
println(2)
}
is being passed to setRunnable. The value of a block is the value of its last expression, so it is passing the result of println(2) to setRunnable. Since that is Unit and setRunnable requires a Runnable, then an implicit is searched for and found, so println(2) is passed to the grossly misnamed blockToRunnable.
Bottom line is, and this is an advice I have given many times already on Stack Overflow (lots of people try to do the same thing) is to get the following in your head:
THERE ARE NO BLOCKS IN SCALA.
There are functions, but not blocks.
Technically, that statement is incorrect -- there are blocks in Scala, but they are not what you think they are, so just completely remove them from your mind. You can learn what blocks in Scala are latter, from a clean slate. Otherwise, you're bound to try to get them to work in ways they don't, or infer that things work in a certain way when they work in a different way.
I liked a lot the explanation given in the first scala puzzle.
In other words, what will be the output of:
List(1, 2).map { i => println("Hi"); i + 1 }
List(1, 2).map { println("Hi"); _ + 1 }