Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Learning Concurrency in Kotlin

You're reading from   Learning Concurrency in Kotlin Build highly efficient and scalable applications

Arrow left icon
Product type Paperback
Published in Jul 2018
Publisher Packt
ISBN-13 9781788627160
Length 266 pages
Edition 1st Edition
Languages
Concepts
Arrow right icon
Author (1):
Arrow left icon
 Castiblanco Torres Castiblanco Torres
Author Profile Icon Castiblanco Torres
Castiblanco Torres
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
1. Hello, Concurrent World! FREE CHAPTER 2. Coroutines in Action 3. Life Cycle and Error Handling 4. Suspending Functions and the Coroutine Context 5. Iterators, Sequences, and Producers 6. Channels - Share Memory by Communicating 7. Thread Confinement, Actors, and Mutexes 8. Testing and Debugging Concurrent Code 9. The Internals of Concurrency in Kotlin 1. Other Books You May Enjoy Index

Iterators


Iterators are particularly useful to go through a collection of elements in order. Some characteristics of Kotlin's iterators are:

  • They can't retrieve an element by index, so elements can only be accessed in order
  • They have the function hasNext(), which indicates whether there are more elements
  • Elements can be retrieved in a single direction only; there's no way to retrieve previous elements
  • They can't be reset, so they can only be iterated once

To create a suspending iterator, we use the builder buildIterator(), passing it a lambda with the body of the iterator. This will return an Iterator<T> where T will be determined by the elements that the iterator yields, unless otherwise specified:

val iterator = buildIterator {
yield(1)
}

In this case, for example, iterator will be of type Iterator<Int>. If for some reason we want to override this definition, we can define a type, and it will work as long as all the values that are yielded are compliant with the type. For example...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime
Visually different images