2017-01-31 13 views
2

私がやりたいどんなときから戻る:休憩や表現が

when(transaction.state) { 
    Transaction.Type.EXPIRED, 
    //about 10 more types 
    Transaction.Type.BLOCKED -> { 
     if (transaction.type == Transaction.Type.BLOCKED && transaction.closeAnyway) { 
      close(transaction) 
      break //close if type is blocked and has 'closeAnyway' flag 
     } 
     //common logic 
    } 
    //other types 
} 

私はbreakを書き込むことはできません。

「ブレーク」と「継続」「のとき」文では許可されていません。ラベルを使用して外側のループを継続/中断することを検討してください。

return/breakからwhenまではどこですか?またはそれを解決する最善の方法は何ですか?

+2

ちょうど 'else'ブロックに "共通ロジック" のものを置くことについて? –

+0

@OliverDain、良いアイデア!しかし、 'break'が必要なすべてのケースを置き換えるのでしょうか? – Feeco

+0

私はブレーク機能がいいと思っています(ただし、いつでもif/elseを行うことができます)。 Kotlinチームが実装する(またはしない)ようになるまで、回避策を提案するだけです。 –

答えて

3

あなたはreturn at labelrunを使用することができます。

方法
when(transaction.state) { 
    Transaction.Type.EXPIRED, 
    //about 10 more types 
    Transaction.Type.BLOCKED -> run { 
     if (transaction.type == Transaction.Type.BLOCKED && transaction.closeAnyway) { 
      close(transaction) 
      [email protected] //close if type is blocked and has 'closeAnyway' flag 
     } 
     //common logic 
    } 
    //other types 
} 
1

ラベルを使用して中断/継続/戻ることができます。例:

[email protected] for (transaction in transactions) { 
    when (transaction.state) { 
     Transaction.Type.EXPIRED, 
     Transaction.Type.BLOCKED -> { 
      [email protected] 
     } 
    } 
} 

詳細については、Returns and Jumps - Kotlin Programming Languageを参照してください。 apply()を使用して周りに

+0

良い回避策ですが、 'when'の後にいくつかのコードがある可能性があるので、答えとして受け入れることはできません。 – Feeco

+0

@Feeco。ありがとうございました。私はあなたの質問を少し誤解したと思う。私は別の答えを掲示します。 – mfulton26

1

仕事:

transaction.apply { 
    when(state) { 
     Transaction.Type.EXPIRED, 
     //about 10 more types 
     Transaction.Type.BLOCKED -> { 
      if (type == Transaction.Type.BLOCKED && closeAnyway) { 
       close(this) 
       [email protected] 
      } 
      //common logic 
     } 
     //other types 
    } 
}