Scala列表foreach,在foreach循环中更新列表

时间:2017-01-09 16:02:04

标签: scala foreach

我刚刚开始使用scala,我正在尝试习惯该语言。我想知道以下是否可能:

我有一个isHidden对象列表,我使用Instruction方法循环。在循环播放时,我能够将元素添加到foreach列表中吗?这是一个代码示例,用于解释我想要的内容:

Instruction

1 个答案:

答案 0 :(得分:1)

对于相当复杂的迭代和替换逻辑,惯用法将是这样的:

public class SimpleIntentService extends IntentService {
    public static final String PARAM_IN_MSG = "in_msg";
    public static final String PARAM_OUT_MSG = "out_msg";
    int time;

    public static final String ACTION_RESP = "org.turntotech.intent.action.MESSAGE_PROCESSED";

    public SimpleIntentService() {
        super("SimpleIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        System.out.println("SimpleIntentService Called");
        String msg = intent.getStringExtra(PARAM_IN_MSG);
        int time = intent.getIntExtra("time", 0);

        // Timer implementation
        if (time == 0 ){
            playSound();
        }

        while(time > 0){

            SystemClock.sleep(5000); // 5 seconds
            time -= 5;
            String resultTxt = msg + time + " seconds remaining";
            Intent broadcastIntent = new Intent();

            broadcastIntent.setAction(ACTION_RESP);
            broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
            broadcastIntent.putExtra(PARAM_OUT_MSG, resultTxt);
            broadcastIntent.putExtra("time", time);

            sendBroadcast(broadcastIntent);
            if (time == 0) {
                playSound();
            }
        }
    }

    Uri alert;

    public void playSound(){
        alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), alert);
        r.play();
    }

    public void onDestroy() {
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), alert);
        r.stop();

        super.onDestroy();
    }
}

此解决方案适用于不可变列表返回不可变列表,根据您的逻辑,它具有不同的值。

如果您想最终破解(添加删除等),您可以使用Java ListIterator类来完成上述所有操作以上:

@tailrec
def idiomaticWay(list: List[Instruction],
                 acc: List[Instruction] = List.empty): List[Instruction] =
  list match {
    case WhileStmt() :: tail =>
      // add element to head of acc
      idiomaticWay(tail, CherryOnTop :: acc)
    case IfStmt() :: tail =>
      // add nothing here
      idiomaticWay(tail, list.head :: acc)
    case Nil => acc
  }

val updatedList = idiomaticWay(List(WhileStmt(), IfStmt()))
println(updatedList) // List(IfStmt(), CherryOnTop)

然而在第二种情况下你不需要scala :(所以我的建议是坚持scala中的不可变数据结构