for loop

Kotlin: A for loop that counts up to some maximum integer value

As a brief note to self, I was just converting some Java code to Kotlin, and the correct way to convert this Java for loop that uses i as a counter:

for (int i=0; i<tabLayout.tabCount; i++) { ...

is with this Kotlin for loop:

for (i in 0 until tabLayout.tabCount) { ...

The key there for me is the 0 until part of the syntax.

How to iterate over a Map in Kotlin (for loop)

Kotlin FAQ: How do I iterate over a Map in Kotlin?

Solution: Here’s an example of how to iterate over a Map in Kotlin using a for loop:

val map = mapOf("a" to 1, "b" to 2, "c" to 3)

for ((k,v) in map) {
    println("value of $k is $v")

Inside that for loop the variables k and v refer to the Map keys and values, respectively.

Example in the Kotlin REPL

Here’s what that looks like in the Kotlin REPL:

Scala for/yield examples (for-loop and yield examples) alvin February 21, 2018 - 10:34am

I just found some notes from when I first began working with Scala, and I was working with the yield keyword in for loops. If you haven't worked with something like yield before, it will be helpful to know how it works. Here's a statement of how the yield keyword works in for loops, based on the documentation in the book, Programming in Scala:

How to process every line in a file with a Unix/Linux shell script

Unix/Linux shell script FAQ: How do I write a Unix or Linux shell script where I "do something" for every line in a text file?

Solution: An easy way to process every line in a text file is to use a Unix/Linux while loop in combination with the Linux cat command, like this:

How to use multiple Futures in a Scala for-comprehension

If you want to create multiple Scala Futures and merge their results together to get a result in a for comprehension, the correct approach is to (a) first create the futures, (b) merge their results in a for comprehension, then (c) extract the result using onComplete or a similar technique.

A Linux shell script to rename files with a counter and copy them

As a brief note today, I was recently looking for all Messages/iMessage files that are stored on my Mac, and I used this shell script to copy all of those files — many of which have the same name — into a directory named tmpdir, giving them all new names during the copy process:

for i in `cat myfiles`
    fname=`basename $i`
    cp $i tmpdir/${count}-${fname}
    count=`expr $count + 1`