working filterIsInstance() helper method for filtering on a sub type

This commit is contained in:
James Strachan
2012-03-23 15:31:43 +00:00
parent dadd288c40
commit a18830ef29
3 changed files with 16 additions and 10 deletions
+4 -4
View File
@@ -5,14 +5,14 @@ import kotlin.support.AbstractIterator
import java.util.*
import java.util.Iterator
/** Filters the iterator for all elements of a certain kind */
inline fun <T, R: T> java.util.Iterator<T>.filterIs(): Iterator<R> = FilterIsIterator<T,R>(this)
/** Filters the iterator for all elements of a certain sub class */
inline fun <T, R: T> java.util.Iterator<T>.filterIsInstance(klass: Class<R>): Iterator<R> = FilterIsIterator<T,R>(this, klass)
private class FilterIsIterator<T, R :T>(val iter: java.util.Iterator<T>) : AbstractIterator<R>() {
private class FilterIsIterator<T, R :T>(val iter: java.util.Iterator<T>, val klass: Class<R>) : AbstractIterator<R>() {
override fun computeNext(): R? {
while (iter.hasNext()) {
val next = iter.next()
if (next is R) {
if (klass.isInstance(next)) {
return next as R
}
}
+2 -2
View File
@@ -225,10 +225,10 @@ protected class PreviousSiblingIterator(var node: Node) : AbstractIterator<Node>
}
/** Returns an [[Iterator]] of all the next [[Element]] siblings */
fun Node.nextElements(): Iterator<Element> = nextSiblings().filterIs<Node, Element>()
fun Node.nextElements(): Iterator<Element> = nextSiblings().filterIsInstance<Node, Element>(javaClass<Element>())
/** Returns an [[Iterator]] of all the previous [[Element]] siblings */
fun Node.previousElements(): Iterator<Element> = previousSiblings().filterIs<Node, Element>()
fun Node.previousElements(): Iterator<Element> = previousSiblings().filterIsInstance<Node, Element>(javaClass<Element>())
/** Returns the attribute value or empty string if its not present */
inline fun Element.attribute(name: String): String {