2016-11-04 78 views
1

我想要做這樣的事情。斯卡拉:在方法多return語句返回未來[布爾]

def foo(s : String): Future[Boolean] = Future { 
    val a = someLongRunningMethod 

    if(!a) 
     return false or throw some exception // what should i return 

    //do some more thing 

    val b= someMoreLongRunningMethod 
    if(b) 
     return true 

    return false 
    } 

但無法使用帶布爾值的返回值。我有類型不匹配錯誤。

Error:(32, 12) type mismatch; 
found : Boolean(false) 
required: scala.concurrent.Future[Boolean] 
    return false 

我是斯卡拉新手。我正在使用foo方法。我不知道這是否是使用它的最佳方式。請建議我應該如何實現它?

val r = foo("Nishant") 
r.onComplete { 
    case Success(result) => { 
    //Do something with my list 
    println("success: " + result) 
    } 
    case Failure(exception) => { 
    //Do something with my error 
    println("failure") 
    } 
} 
val re = Await.result(r, 10 second) 
+0

您需要首先看了一則關於'Future'類型是如何工作的教程(順便說一句使用這樣的回報是不是斯卡拉idomatic) – cchantep

+0

http://tpolecat.github.io/2014/05/09/return html的 – michaJlS

+0

我讀了一些教程,但個個都與單一的if/else塊的例子。你能推薦一些很好的教程嗎 –

回答

1

在Scala中在塊最後一個表達式是代碼塊或函數的返回值。關鍵字返回在scala中是可選的。

請注意,我們只運行如果任務返回true,第二個任務。如果第一個任務返回false,那麼我們就完成了。這意味着第一個任務是我們作爲決策者的計算非常重要。

你的版本修改:

def longRunning1: Boolean = ??? 
    def longRunning2: Boolean = ??? 

    import scala.concurrent.ExecutionContext.Implicits.global 

    def foo(s : String): Future[Boolean] = Future { 
    val a: Boolean = longRunning1 
    if(a) { 
     val b: Boolean = longRunning2 
     b 
    } else false 
    } 

版本1:後來

潤期貨(計算或長時間運行的方法),同時,選擇的結果。在這裏,我們放棄了第二次計算的結果,如果我們考慮還是希望第一個計算的結果。

import scala.concurrent.ExecutionContext.Implicits.global 

    def foo(s: String): Future[Boolean] = { 

    val f1 = Future { 
     Thread.sleep(20000) //Just to simulate long running task 
     Random.nextBoolean() 
    } 

    val f2 = Future { 
     Thread.sleep(1000) //Just to simulate long running task 
     Random.nextBoolean() 
    } 

    (f1 zip f2) map { 
     case (false, _) => false 
     case (true, f2Result) => f2Result 
     case _ => false 
    } 

    } 

版本2:

運行第一種方法,然後根據所述第一方法的結果嘗試運行其他之後的第二個方法之一。計算使用地圖鏈接。

import scala.concurrent.ExecutionContext.Implicits.global 

    def foo(s: String): Future[Boolean] = { 

    val f1 = Future { 
     Thread.sleep(20000) //Just to simulate long running task 
     Random.nextBoolean() 
    } 

    f1.map { result => 
     if (result) result 
     else { 
     Thread.sleep(1000) //Just to simulate long running task 
     Random.nextBoolean() 
     } 
    } 

    } 
+0

在版本2中..如果logRunningTash可以拋出並且哪個更好,當兩個任務都依賴時,如何處理異常,即第二個需要第一個輸入嗎? –

+0

@NishantKumar讓我更新異常情況下的問題 – pamu

+0

@NishantKumar版本:2比版本1更好。從例外的角度來看,v1和v2都不錯 – pamu