From cb1a68cfda0eed0a5473dcb3c679095c003273b6 Mon Sep 17 00:00:00 2001 From: Max Vogler Date: Mon, 21 Sep 2015 00:59:39 +0200 Subject: [PATCH] Allow getting MenuItems as Sequence --- dsl/static/src/common/menuItemsSequences.kt | 52 +++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 dsl/static/src/common/menuItemsSequences.kt diff --git a/dsl/static/src/common/menuItemsSequences.kt b/dsl/static/src/common/menuItemsSequences.kt new file mode 100644 index 00000000..dc61eabb --- /dev/null +++ b/dsl/static/src/common/menuItemsSequences.kt @@ -0,0 +1,52 @@ +/* + * Copyright 2015 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@file:JvmMultifileClass +@file:JvmName("MenuItemsSequencesKt") +package org.jetbrains.anko + +import android.view.Menu +import android.view.MenuItem +import java.util.* + +fun Menu.itemsSequence(): Sequence = MenuItemsSequence(this) + +private class MenuItemsSequence(private val menu: Menu) : Sequence { + override fun iterator(): Iterator { + return MenuItemIterator(menu) + } + + private class MenuItemIterator(private val menu: Menu) : Iterator { + private var index = 0 + private val count = menu.size() + + override fun next(): MenuItem { + if (!hasNext()) { + throw NoSuchElementException() + } + + return menu.getItem(index++) + } + + override fun hasNext(): Boolean { + if (count != menu.size()) { + throw ConcurrentModificationException() + } + + return index < count + } + } +}