asSequence

inline fun <T> Sequence<T>.asSequence(): Sequence<T>(source)

Returns this sequence as a Sequence.

Since Kotlin

1.0

Creates a sequence that returns all elements from this iterator. The sequence is constrained to be iterated only once.

Since Kotlin

1.0

Samples

import kotlin.test.*

fun main() { 
   //sampleStart 
   val array = arrayOf(1, 2, 3)

// create a sequence with a function, returning an iterator
val sequence1 = Sequence { array.iterator() }
println(sequence1.joinToString()) // 1, 2, 3
println(sequence1.drop(1).joinToString()) // 2, 3

// create a sequence from an existing iterator
// can be iterated only once
val sequence2 = array.iterator().asSequence()
println(sequence2.joinToString()) // 1, 2, 3
// sequence2.drop(1).joinToString() // <- iterating sequence second time will fail 
   //sampleEnd
}

Creates a sequence that returns all values from this enumeration. The sequence is constrained to be iterated only once.

Since Kotlin

1.0

Samples

import kotlin.test.*

fun main() { 
   //sampleStart 
   val numbers = java.util.Hashtable<String, Int>()
numbers.put("one", 1)
numbers.put("two", 2)
numbers.put("three", 3)

// when you have an Enumeration from some old code
val enumeration: java.util.Enumeration<String> = numbers.keys()

// you can wrap it in a sequence and transform further with sequence operations
val sequence = enumeration.asSequence().sorted()
println(sequence.toList()) // [one, three, two]

// the resulting sequence is one-shot
// sequence.toList() // will fail 
   //sampleEnd
}