簡體   English   中英

無法在 Scala 中突破 foreach 循環

[英]Cannot breakout of foreach loop in scala

我有下面的代碼

> .foreach("${plist}", "newshole") {
>        exec(
>          http("get the user id")
>            .get("${newshole}/jcr:content.1.json")
>            .headers(headers_2)
>            .check(bodyString.saveAs("Res1"))
>        )
>        exec(session => {
>          var mynewshole = session("Res1").as[String]
>          if (!mynewshole.contains("testingInProgress")) {
>            println("Doesn't contain: " + mynewshole)
>            (http("post the user id")
>              .post("${newshole}/jcr:content")
>              .headers(headers_2)
>              .formParam("testingInProgress", session.userId))
>            exec(http("Create print package")
>              .post("/bin/cqtg-create-print-package.do")
>              .headers(headers_2)
>              .formParam("newsholeId", "${plist}")
>              .formParam("digitalMasterId", "1adpy8")
>              .check(status.is(200)))
> 
>          }
>          session
>        })   
>      }

我想擺脫:

> if (!mynewshole.contains("testingInProgress")) {
>            println("Doesn't contain: " + mynewshole)
>            (http("post the user id")
>              .post("${newshole}/jcr:content")
>              .headers(headers_2)
>              .formParam("testingInProgress", session.userId))
>            exec(http("Create print package")
>              .post("/bin/cqtg-create-print-package.do")
>              .headers(headers_2)
>              .formParam("newsholeId", "${plist}")
>              .formParam("digitalMasterId", "1adpy8")
>              .check(status.is(200)))
> 
>          }
>          session

基本上我想在我的第一個條件滿足時從循環中跳出。所以我想按照 scala 教程使用下面的代碼,但不知道在哪里放置可破解命令,因為它給了我錯誤。

> breakable{
>             code ()
>          break;
>            }

但不知道把它放在哪里。任何想法????

Scala 並沒有真正提供任何易於使用的break / continue控制流原語。 這不是做事的功能方式。

Scala 集合上可用的大多數方法,如foreach ,旨在檢查/修改整個集合。 例外情況包括: containscorrespondsexistsforallindexWhere等,你會注意到,大多數(所有?)處理布爾值,無論是作為一個參數(謂語功能)或作為返回類型。

如果您的算法無法重新設計以使用這些惰性評估方法之一,那么我建議您遵循 @pietro909 的建議並將其重新設計為遞歸函數,該函數在每次調用/遞歸時測試一個或多個退出條件。

我知道這是不是真的你要的,你可以通過將實現你想要的這是真的breakable在你的代碼塊,但是如果你查看源代碼,你會看到符拋出/捕獲異常實現,這是非常低效的,通常值得避免。

但是,如果您決心走這條路,這應該會提供一些指導:

scala> import util.control.Breaks
import util.control.Breaks

scala> val mybreaks = new Breaks
mybreaks: scala.util.control.Breaks = scala.util.control.Breaks@69ea3742

scala> import mybreaks.{break, breakable}
import mybreaks.{break, breakable}

scala> breakable {
     | (1 to 34).foreach(x => if (x > 9) break else println(x))
     | println("all done")
     | }
1
2
3
4
5
6
7
8
9

注意: break不僅僅終止foreach()語句,它打破了整個breakable塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM