# forEach

Published articles for forEach.

This is one page of public article previews, not the complete archive. Follow Next page to continue. Summaries are not the original full articles.

## Choosing Wisely: for vs. forEach in Kotlin (A Thinking Dev's Perspective)

DevFeed: [Choosing Wisely: for vs. forEach in Kotlin (A Thinking Dev's Perspective)](<https://devfeed.tech/articles/choosing-wisely-for-vs-foreach-in-kotlin-a-thinking-dev-s-perspective-24905.md>)

Original publisher: [Read original article](<https://blog.blundellapps.co.uk/choosing-wisely-for-vs-foreach-in-kotlin-a-thinking-devs-perspective/>)

Author: blundell

Published: 2025-04-04T14:25:30Z

Content type: article

Language: en

Sources: [Blundell](<https://devfeed.tech/sources/blundell.md>)

Topics: [Kotlin](<https://devfeed.tech/topics/kotlin.md>), [Programming](<https://devfeed.tech/topics/programming.md>), [Code](<https://devfeed.tech/topics/code.md>)

Tags: [androiddev](<https://devfeed.tech/tags/androiddev.md>), [code](<https://devfeed.tech/tags/code.md>), [dev](<https://devfeed.tech/tags/dev.md>), [foreach](<https://devfeed.tech/tags/foreach.md>), [functional](<https://devfeed.tech/tags/functional.md>), [intermediate](<https://devfeed.tech/tags/intermediate.md>), [kotlin](<https://devfeed.tech/tags/kotlin.md>), [loops](<https://devfeed.tech/tags/loops.md>), [programming](<https://devfeed.tech/tags/programming.md>), [readability](<https://devfeed.tech/tags/readability.md>), [reference](<https://devfeed.tech/tags/reference.md>), [reference-androiddev-kotlin](<https://devfeed.tech/tags/reference-androiddev-kotlin.md>), [structure](<https://devfeed.tech/tags/structure.md>), [syntax](<https://devfeed.tech/tags/syntax.md>)

### AI overview

This Kotlin development article argues against reflexively choosing forEach. It compares forEach with traditional for loops and dedicated functional operators, emphasizing readability, explicit control, side effects, and clearer data flow.

### Source excerpt

The forEach loop, are you using it without thinking? In Kotlin, empirically forEach is often the go-to loop, it's pragmatically close at reach in the IDE auto-complete, but is it always the right choice? This post argues that for loops deserve more consideration, offering clarity and control that forEach sometimes lacks. Let's discuss why a [...] The post Choosing Wisely: for vs. forEach in Kotlin (A Thinking Dev's Perspective) first appeared on Blundell.

## Collections: Lists and Sets

DevFeed: [Collections: Lists and Sets](<https://devfeed.tech/articles/collections-lists-and-sets-25049.md>)

Original publisher: [Read original article](<https://typealias.com/start/kotlin-collections/>)

Author: author@typealias.com (Dave Leeds)

Published: 2022-04-18T00:00:00Z

Content type: tutorial

Language: en

Sources: [Dave Leeds on Kotlin - typealias.com](<https://devfeed.tech/sources/dave-leeds-on-kotlin-typealias-com.md>)

Topics: [Kotlin](<https://devfeed.tech/topics/kotlin.md>), [Code](<https://devfeed.tech/topics/code.md>), [Learning](<https://devfeed.tech/topics/learning.md>)

Tags: [code](<https://devfeed.tech/tags/code.md>), [collection-operations](<https://devfeed.tech/tags/collection-operations.md>), [collections](<https://devfeed.tech/tags/collections.md>), [filter](<https://devfeed.tech/tags/filter.md>), [foreach](<https://devfeed.tech/tags/foreach.md>), [introduction](<https://devfeed.tech/tags/introduction.md>), [kotlin](<https://devfeed.tech/tags/kotlin.md>), [learn-to-program](<https://devfeed.tech/tags/learn-to-program.md>), [learning](<https://devfeed.tech/tags/learning.md>), [list](<https://devfeed.tech/tags/list.md>), [map](<https://devfeed.tech/tags/map.md>), [programming](<https://devfeed.tech/tags/programming.md>), [set](<https://devfeed.tech/tags/set.md>)

### AI overview

A Kotlin tutorial introduces collections by explaining how to group values and begins demonstrating lists and sets through a book-list example.

### Source excerpt

So far, we've only worked with variables as individual values. Writing Kotlin becomes so much more interesting once we start putting values together in such a way that we can work with them as a collection. To learn about collections, let's visit Libby, a bright young lady who's always got a book nearby! Let's put things together! Libby is a voracious reader. She's always on the lookout for a great novel, so whenever someone tells her about a good book, she jots down the title on a list that she keeps on a sheet of paper.

## SwiftUI: впечатления iOS-разработчика о реактивном UI-фреймворке и его синтаксисе

DevFeed: [SwiftUI: впечатления iOS-разработчика о реактивном UI-фреймворке и его синтаксисе](<https://devfeed.tech/articles/article-34264.md>)

Original publisher: [Read original article](<https://tonsky.livejournal.com/324649.html>)

Published: 2020-01-18T15:36:57Z

Content type: opinion

Language: ru

Sources: [Tonsky Стой под стрелой](<https://devfeed.tech/sources/tonsky.md>)

Topics: [SwiftUI](<https://devfeed.tech/topics/swiftui.md>), [iOS](<https://devfeed.tech/topics/ios.md>), [ui](<https://devfeed.tech/topics/ui.md>)

Tags: [foreach](<https://devfeed.tech/tags/foreach.md>), [ios](<https://devfeed.tech/tags/ios.md>), [livejournal](<https://devfeed.tech/tags/livejournal.md>), [padding](<https://devfeed.tech/tags/padding.md>), [swiftui](<https://devfeed.tech/tags/swiftui.md>), [tag-5e1c061eda96](<https://devfeed.tech/tags/tag-5e1c061eda96.md>), [tag-c40b78a8c8a6](<https://devfeed.tech/tags/tag-c40b78a8c8a6.md>), [tag-d16a2c26554f](<https://devfeed.tech/tags/tag-d16a2c26554f.md>), [tag-e3028c5e0ab2](<https://devfeed.tech/tags/tag-e3028c5e0ab2.md>), [ui](<https://devfeed.tech/tags/ui.md>), [view](<https://devfeed.tech/tags/view.md>)

### AI overview

An experienced iOS developer shares impressions of SwiftUI after using it for roughly six months and releasing two production applications. The article praises its reactive, data-driven UI model and previews while criticizing its syntax, element-count limitation, opaque types, and inconsistent modifier and container design.

### Source excerpt

Если вдруг вы еще не знаете, примерно полгода назад Эппл анонсировало новый UI фреймворк -- SwiftUI. Событие очень серьезное, и как iOS разработчик со стажем я тут же переключился на него -- сначала попробовать, а потом уже и выпускать production приложения. Спустя полгода и два заапрувленных релиза, хочу поделиться с вами мыслями о SwiftUI. Во-первых, то, что Эппл выпустило нормальный реактивный data-driven UI фреймворк, заслуживает исключительно всяческих похвал. Правильный тренд, правильный подход, _почти_ интерактивное превью, все вовремя и к месту. Нам, iOS-программистам, чего-то такого сильно не хватало. Во-вторых (и тут уже о сомнительном), количество синтаксического сахара, которым они там обмазываются, вызывает, скажем так, удивление. Им пришлось серьезно расширить язык, чтобы вместо условно VStack( Image(uiImage: image), Text(title), Text(subtitle) ) можно было писать VStack { Image(uiImage: image) Text(title) Text(subtitle) } На что только люди не пойдут чтобы избежать споров о том где ставить запятую! Работает это благодаря вот такому вот прекрасному интерфейсу: То есть не только не очень понятно зачем так усложнять себе жизнь, но еще и больше 10 элементов не засунешь. Может быть создатели руководствовались правилом 7±2 и решили, что пользователи айфона не смогут всерьез осознать более 10 одновременных элеметов на экране. То что в этом интерфейсе пропилена специальная дырка для if напрягает если честно еще больше: Не самим фактом дырки, а вопросом, где же собственно дырки под все остальное? (на самом деле, если хочется больше 10 элементов, есть целый специальный компонент -- ForEach, который -- уберите детей от экрана! -- принимает список) (этот курьез и необходимость вводить opaque types заставляет задуматься, насколько сильно нам вообще нужна статическая типизация и какой ценой. Конечно, сторонники статической типизации скажут, что это просто типизация неправильная, вот была бы правильная и проблем бы не было -- что, в общем-то, универсальный аргумент, удобн

## Functional operations with collections in Kotlin (KAD 11)

DevFeed: [Functional operations with collections in Kotlin (KAD 11)](<https://devfeed.tech/articles/functional-operations-with-collections-in-kotlin-kad-11-27166.md>)

Original publisher: [Read original article](<https://antonioleiva.com/functional-operations-collections-kotlin>)

Published: 2017-02-02T00:00:00Z

Content type: tutorial

Language: en

Sources: [Antonio Leiva](<https://devfeed.tech/sources/antonio-leiva.md>)

Topics: [Kotlin](<https://devfeed.tech/topics/kotlin.md>), [Code](<https://devfeed.tech/topics/code.md>), [Android](<https://devfeed.tech/topics/android.md>)

Tags: [code](<https://devfeed.tech/tags/code.md>), [collections](<https://devfeed.tech/tags/collections.md>), [filter](<https://devfeed.tech/tags/filter.md>), [foreach](<https://devfeed.tech/tags/foreach.md>), [functional](<https://devfeed.tech/tags/functional.md>), [kotlin](<https://devfeed.tech/tags/kotlin.md>), [list](<https://devfeed.tech/tags/list.md>), [map](<https://devfeed.tech/tags/map.md>), [sorting](<https://devfeed.tech/tags/sorting.md>)

### AI overview

This tutorial introduces functional operations on Kotlin collections, including forEach, map, filter, first, last, and sorting. It explains how these operations simplify collection handling compared with Java and notes alternatives such as nullable results when no matching element is found.

### Source excerpt

Everything Android, Kotlin and other random topics

## Getting the current filename with Spark and HDFS

DevFeed: [Getting the current filename with Spark and HDFS](<https://devfeed.tech/articles/getting-the-current-filename-with-spark-and-hdfs-20849.md>)

Original publisher: [Read original article](<http://themodernlife.net/scala/spark/hadoop/hdfs/2014/09/28/spark-input-filename/>)

Published: 2014-09-28T11:50:13Z

Content type: tutorial

Language: en

Sources: [Ian Hummel](<https://devfeed.tech/sources/ian-hummel.md>)

Topics: [Apache Spark](<https://devfeed.tech/topics/spark.md>), [Hadoop](<https://devfeed.tech/topics/hadoop.md>)

Tags: [apache-spark](<https://devfeed.tech/tags/apache-spark.md>), [foreach](<https://devfeed.tech/tags/foreach.md>), [hadoop](<https://devfeed.tech/tags/hadoop.md>), [hdfs](<https://devfeed.tech/tags/hdfs.md>), [map](<https://devfeed.tech/tags/map.md>), [reduce](<https://devfeed.tech/tags/reduce.md>), [scala](<https://devfeed.tech/tags/scala.md>), [spark](<https://devfeed.tech/tags/spark.md>), [subclass](<https://devfeed.tech/tags/subclass.md>)

### AI overview

A tutorial shows how to obtain the filename being processed in a Spark map/reduce job. It uses Spark 1.1.0's HadoopRDD.mapPartitionsWithInputSplit with FileSplit, and notes that the approach requires an InputFormat subclass of FileInputFormat.

### Source excerpt

It's occasionally useful when writing map/reduce jobs to get a hold of the current filename that's being processed. There's a few ways to do this, depending on the version of Spark that you're using. Spark 1.1.0 introduced a new method on HadoopRDD that makes this super easy: import org.apache.hadoop.io.LongWritable import org.apache.hadoop.io.Text import org.apache.hadoop.mapred.{FileSplit, TextInputFormat} import org.apache.spark.rdd.HadoopRDD // Create the text file val text = sc.hadoopFile("file:///tmp/files", classOf[TextInputFormat], classOf[LongWritable], classOf[Text], sc.defaultMinPartitions) // text: org.apache.spark.rdd.RDD[(org.apache.hadoop.io.LongWritable, org.apache.hadoop.io.Text)] = file:///tmp/files HadoopRDD[2] at hadoopFile at <console>:16 // Cast to a HadoopRDD val hadoopRdd = text.asInstanceOf[HadoopRDD[LongWritable, Text]] // hadoopRdd: org.apache.spark.rdd.HadoopRDD[org.apache.hadoop.io.LongWritable,org.apache.hadoop.io.Text] = file:///tmp/files HadoopRDD[2] at hadoopFile at <console>:16 val fileAndLine = hadoopRdd.mapPartitionsWithInputSplit { (inputSplit, iterator) ⇒ val file = inputSplit.asInstanceOf[FileSplit] iterator.map { tpl ⇒ (file.getPath, tpl._2) } } fileAndLine.foreach(println) // prints lines like (file:/tmp/files/part-00000,line1...), (file:/tmp/files/part-00000,line2...), ... There are a few things to note: - You can't simply use sc.textFile because under the hood, the textFile method actually maps the resulting HadoopRDD, returning a MappedRDD which is not what we want - This will only work if your InputFormat is a subclass of FileInputFormat - mapPartitionsWithInputSplit returns a new iterator, in this case we simply map over it (which is done lazily!) to include the split's filename

## The Difference Between :x:element and :x:primitive

DevFeed: [The Difference Between :x:element and :x:primitive](<https://devfeed.tech/articles/the-difference-between-x-element-and-x-primitive-22031.md>)

Original publisher: [Read original article](<https://codebeforethehorse.tumblr.com/post/35419887698>)

Author: Codebeforethehorse

Published: 2012-11-10T18:16:00Z

Content type: tutorial

Language: en

Sources: [Stefan Parker](<https://devfeed.tech/sources/stefan-parker.md>)

Topics: [XSS](<https://devfeed.tech/topics/xss.md>), [Sanitization](<https://devfeed.tech/topics/sanitization.md>), [HTML](<https://devfeed.tech/topics/html.md>), [JSON](<https://devfeed.tech/topics/json.md>), [html elements](<https://devfeed.tech/topics/html-elements.md>), [Ajax](<https://devfeed.tech/topics/ajax.md>)

Tags: [foreach](<https://devfeed.tech/tags/foreach.md>), [function](<https://devfeed.tech/tags/function.md>), [html](<https://devfeed.tech/tags/html.md>), [html-elements](<https://devfeed.tech/tags/html-elements.md>), [json](<https://devfeed.tech/tags/json.md>), [payload](<https://devfeed.tech/tags/payload.md>), [protection](<https://devfeed.tech/tags/protection.md>), [render](<https://devfeed.tech/tags/render.md>), [rest](<https://devfeed.tech/tags/rest.md>), [xhp](<https://devfeed.tech/tags/xhp.md>), [xss](<https://devfeed.tech/tags/xss.md>)

### AI overview

This article explains when to use :x:element versus :x:primitive in XHP. It recommends :x:element for most cases because its render() method produces more XHP and supports recursive rendering, while :x:primitive ultimately stringifies the result. It identifies custom HTML nodes and non-HTML output such as JSON AJAX responses as the main reasons to use :x:primitive.

### Source excerpt

I was recently asked to clarify the differences between :x:element and :x:primitive, and when to use each one. It's actually pretty simple; the basic rule of thumb is this: always use :x:element. If you're only doing simple things in XHP you can stop reading now, but for the rest of you I'll get into the rare instances where you might use :x:primitive. First, the main difference. :x:element implements the render() method, which returns more XHP while :x:primitive implements to stringify() method, which returns a string. When you echo XHP to the page, it recursively calls render() on itself until it returns an :x:primitive. It will continue to do this to any children of an :x:primitive as well. Once the entire tree is just :x:primitives (usually meaning just HTML nodes) it stringify()s it. So why the difference? The big reason was that we can put XSS protection in all HTML elements and so long as you just return HTML nodes you'll never have to worry about input sanitization again. There are two cases where you would want to create an :x:primitive though. The first being if you wanted to create a custom HTML node. Let's say you wanted to create a <foo> tag for your own purposes. All you would need to do is extend :xhp:html-element (which extends :x:primitive) and define its tag name. class :foo extends :xhp:html-element { protected $tagname = 'foo'; } Pretty simple. You could define custom attributes and children restrictions too if you so desired. The other reason you would extend :x:primitive is if you wanted to return something other than HTML. Consider an AJAX response that returns a JSON object. You might construct an object that behaves like this: class :ajax:response extends :x:primitive { attribute array payload; attribute array errors; protected function stringify() { $html = ''; foreach ($this->getChildren() as $child) { $html .= :x:base::renderChild($child); } $response = array( 'payload' => $this->getAttribute('payload'), 'errors' => $this->getAttribute('e

## Async sequential workflows

DevFeed: [Async sequential workflows](<https://devfeed.tech/articles/async-sequential-workflows-38412.md>)

Original publisher: [Read original article](<https://khmylov.com/2012/04/async-sequential-workflows/>)

Author: Andrew Khmylov

Published: 2012-04-26T00:00:00Z

Content type: tutorial

Language: ru

Sources: [Despite the odds](<https://devfeed.tech/sources/despite-the-odds.md>)

Topics: [async](<https://devfeed.tech/topics/async.md>), [async/await](<https://devfeed.tech/topics/async-await.md>), [client](<https://devfeed.tech/topics/client.md>), [.NET](<https://devfeed.tech/topics/net.md>)

Tags: [async](<https://devfeed.tech/tags/async.md>), [await](<https://devfeed.tech/tags/await.md>), [client](<https://devfeed.tech/tags/client.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [foreach](<https://devfeed.tech/tags/foreach.md>), [observable](<https://devfeed.tech/tags/observable.md>), [request](<https://devfeed.tech/tags/request.md>), [yield](<https://devfeed.tech/tags/yield.md>)

### AI overview

This tutorial compares synchronous and asynchronous implementations of sequential workflows for downloading files with .NET WebClient. It explains how sequential requests can be represented with observables and how async/await can reduce the work needed to describe the control flow.

### Source excerpt

В последнее время всё чаще приходится сталкиваться с задачами, требующими выполнения последовательных асинхронных операций. Примером может служить загрузка файлов на мобильном устройстве. Учитывая что телефон может работать на слабом мобильном соединении, нам вряд ли удастся получить прирост производительности от параллельной загрузки. Да и стандартный класс WebClient, представленный в BCL не очень дружит с concurrent operations (точнее вообще не дружит). Создавать новый экземпляр на каждый запрос кажется идейно неправильным, так что попробуем обойтись одним веб-клиентом, обрабатывающим множество последовательных запросов. Для начала - тривиальная синхронная реализация (которая конечно же не будет работать на WP7 из-за отсутствия синхронных методов у WebClient'а): public IEnumerable<string> Handle(IEnumerable<Uri> requests) { var client = new WebClient(); foreach (var request in requests) { yield return client.DownloadString(request); } } Разработчику, использующему асинхронную версии, скорее всего захочется узнать о моменте завершении загрузок. Не будем плохими мальчиками/девочками и отбросим мысли о EAP и ручном CPS. Довольно очевидным решением будет представить наши ожидающие загрузки файлы в виде потока событий при помощи observables. К сожалению, WebClient использует EAP для своих асинхронных операций, поэтому код становится чуть более неопрятным: public IObservable<string> HandleAsync(IList<Uri> requests) { var client = new WebClient(); var subject = new Subject<string>(); var enumerator = requests.GetEnumerator(); Action takeNext = () => { if (enumerator.MoveNext()) { client.DownloadStringAsync(enumerator.Current); } else { subject.OnCompleted(); } }; client.DownloadStringCompleted += (s, e) => { if (e.Error != null) { subject.OnError(e.Error); } else { subject.OnNext(e.Result); takeNext(); } }; takeNext(); return subject; } В обоих случаях мы по сути описываем корутины, передающие управление в момент окончания обработки запроса. В синхронной реализации компи