2016-03-08 28 views
3

试图了解为什么以下表达式产生未来[没有],而不是未来未来结果[列表[INT]]理解为什么有用于理解产生未来[没有]

def foo(): Future[List[Int]] = Future(List(1,2,3,3,3,4,4,4)) 
def bar(): Future[Nothing] =for { 
    fooList <- foo() 
    f <- fooList.distinct 
} yield f 
当然

,这是简化的示例,我可以直接返回fooList。但我想了解越来越Future[Nothing]而不是Future[List[Int]]

+0

我得到的控制台上的类型不匹配,这是我所期待的。 – ziggystar

回答

6

我得到一个编译错误的代码,这是意料之中的,因为fooList.distinct本来应该用于提取<-上班就可以了一Future的原因。

scala> def foo() = Future(List(1,2,2,3)) 
foo:()scala.concurrent.Future[List[Int]] 


scala> for(fooList <- foo(); f <- fooList.distinct) yield f 
<console>:17: error: type mismatch; 
found : List[Int] 
required: scala.concurrent.Future[?] 
       for(fooList <- foo(); f <- fooList.distinct) yield f 
            ^

此代码编译:

scala> for(fooList <- foo(); f = fooList.distinct) yield f 
res4: scala.concurrent.Future[List[Int]] = [email protected] 

而这种代码也(包装调用distinct成未来):

scala> for(fooList <- foo(); f <- Future(fooList.distinct)) yield f 
res5: scala.concurrent.Future[List[Int]] = [email protected] 
res4: scala.concurrent.Future[List[Int]] = [email protected] 
+0

谢谢。 (它在IDE上编译,应该试过repl) – igx

+0

这个答案没有解释为什么OP的方法无效。 – Haspemulator

+0

@Haspemulator第一句话呢?我可以更深入地解释它。但也许这并不总是有用的。 – ziggystar

2

Scala的换理解只是语法糖方法flatMap,mapfilter。 A码

for { 
    x1 <- e1 
    x2 = e2 
    x3 <- e3 if e4 
    x4 <- e5 
} yield e6 

转化为(或等价的东西)

e1.flatMap(x1 => 
e2.map(x2 => 
e3.filter(x3 => e4).flatMap(x3 => 
e5.map(x4 => e6) 

换理解你的榜样变得

foo().flatMap(fooList => fooList.distinct.map(f => f)) 

这相当于

foo().flatMap(fooList => fooList.distinct) 

由于map(id) = id的定义是什么Functor是。方法foo().flatMap需要List[Int] ⇒ Future[S]类型的参数。但功能fooList => fooList.distinct的类型是List[Int] => List[Int]。编译器检查提供的类型是否是预期类型的​​子类型。在你的情况下,检查落到:List[Int]Future[S]某种类型S一个亚型。我不知道为什么S的执行类型是Nothing,但它可能与Future是协变的(因为任何Functor都应该)有关。

给定类型的将来Future[T]mapflatMap都产生一个Future[S]但不同的是:

  • map需要T => S类型的参数。 语法x = ...
  • flatMap需要T => Future[S]类型的参数。 语法x <- ...

你想用的方法则map这给

for (fooList <- foo()) 
yield fooList.distinct 

foo().map(fooList => fooList.distinct) 
相关问题