The snippets are under the CC-BY-SA license.

Creative Commons Attribution-ShareAlike 3.0

Logo

Programming-Idioms.org

  • The snippets are under the CC-BY-SA license.
  • Please consider keeping a bookmark
  • (instead of printing)
Kotlin
1
Print a literal string on standard output
println("Hello world!")
2
Loop to execute some code a constant number of times
(0..9).forEach {
    println("Hello")
}
Alternative implementation:
repeat(10) {
    println("Hello")
}
Alternative implementation:
for(x in 1..10) {
     println("Hello")
}
3
Like a function which doesn't return any value, thus has only side effects (e.g. Print to standard output)
fun finish(name: String) { 
  println("My job here is done. Goodbye $name") 
}
4
Create a function which returns the square of an integer
fun square(x: Int) = x * x
5
Declare a container type for two floating-point numbers x and y
data class Point(val x: Float, val y: Float)
6
Do something with each item x of the list (or array) items, regardless indexes.
items.forEach { doSomething(it) }
Alternative implementation:
items.forEach(::doSomething)
Alternative implementation:
for (x in items) doSomething(x)
7
Print each index i with its value x from an array-like collection items
items.forEachIndexed { i, x -> 
  println("i=$i x=$x") 
}
8
Create a new map object x, and provide some (key, value) pairs as initial content.
val x = mapOf("one" to 1, "two" to 2)
Alternative implementation:
val x = mutableMapOf<String, Int>().apply { 
    this["one"] = 1
    this["two"] = 2
}
Alternative implementation:
val x = mutableMapOf<String, Int>()
x["one"] = 1
x["two"] = 2
9
The structure must be recursive because left child and right child are binary trees too. A node has access to children nodes, but not to its parent.
data class Node(
    val key: Int,
    val left: Node? = null,
    val right: Node? = null
)
10
Generate a random permutation of the elements of list x
x.shuffle()
Alternative implementation:
val y = x.shuffled()
11
The list x must be non-empty.
list.random()
12
Check if the list contains the value x.
list is an iterable finite container.
x in list
Alternative implementation:
list.contains(x)
13
Access each key k with its value x from an associative array mymap, and print them.
mymap.entries.forEach { print("${it.key} ${it.value}") }
Alternative implementation:
mymap.forEach { k, v -> println("$k -> $v") }
14
Pick a random number greater than or equals to a, strictly inferior to b. Precondition : a < b.
Random.nextDouble(a,b)
15
Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.
fun pick(a: Int, b: Int): Int {
    return (a..b).random()
}
16
Call a function f on every node of binary tree bt, in depth-first infix order
fun dfs(bt: BinaryTree) {
    bt.left?.let { dfs(it) }
    f(bt)
    bt.rigth?.let { dfs(it) }
}
19
Reverse the order of the elements of the list x.
This may reverse "in-place" and destroy the original ordering.
x.reverse()
Alternative implementation:
x = x.reversed()
Alternative implementation:
val reversedView = x.asReversed()
20
Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.
fun search(m: Array<Array<Int>>, x: Int): Pair<Int, Int>? {
    m.forEachIndexed { i, row ->
        row.forEachIndexed { j, value ->
            if (value == x) {
                return Pair(i, j)
            }
        }
    }
    return null
}
21
Swap the values of the variables a and b
a = b.also { b = a }
22
Extract the integer value i from its string representation s (in radix 10)
val i = s.toInt()
Alternative implementation:
val i = s.toIntOrNull()
23
Given a real number x, create its string representation s with 2 decimal digits following the dot.
s = "%.2f".format(x)
26
Declare and initialize a matrix x having m rows and n columns, containing real numbers.
val x = Array(m, { DoubleArray(n) })
27
Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.
val x = Array(m, { Array(n, { DoubleArray(p) } ) } )
28
Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.
items.sortedBy { it.p }
29
Remove i-th item from list items.
This will alter the original list or return a new list, depending on which is more idiomatic.
Note that in most languages, the smallest valid value for i is 0.
items.removeAt(i)
30
Launch the concurrent execution of the procedure f with parameter i from 1 to 1000.
Tasks are independent and f(i) doesn't return any value.
Tasks need not run all at the same time, so you may use a pool.
fun main() = runBlocking {
    repeat(1000) {
        launch {
            f(it)
        }
    }
}
31
Create the recursive function f which returns the factorial of the non-negative integer i, calculated from f(i-1)
fun f(i: Int): Int = when (i) {
    0 -> 1
    else -> i * f(i - 1)
}
Alternative implementation:
fun f(i: Int) = if (i == 0) 1 else i * f(i - 1)
32
Create function exp which calculates (fast) the value x power n.
x and n are non-negative integers.
fun exp(x: Int, n: Int): Int = when {
    n == 0 -> 1
    n == 1 -> x
    n % 2 == 0 -> exp(x * x, n / 2)
    else -> x * exp(x * x, (n - 1) / 2)
}
38
Find substring t consisting in characters i (included) to j (excluded) of string s.
Character indices start at 0 unless specified otherwise.
Make sure that multibyte characters are properly handled.
val t = s.substring(i, j)
39
Set the boolean ok to true if the string word is contained in string s as a substring, or to false otherwise.
val ok = s.contains(word)
Alternative implementation:
val ok = word in s
40
Declare a Graph data structure in which each Vertex has a collection of its neighbouring vertices.
inline class VertexId(val id: Int)
data class Vertex(val id: VertexId, val neighbours: Set<VertexId>)
data class Graph(val vertices: Set<Vertex>)
41
Create the string t containing the same characters as the string s, in reverse order.
The original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.
val t = s.reversed()
43
Look for a negative value v in 2D integer matrix m. Print it and stop searching.
loop@ for (x in 0..7) {
  for (y in 0..7) {
    val v = m[x][y]
    if ( v < 0) {
       println("found a negative value at [$x][$y]: $v")
       break@loop
     }
  }
}
44
Insert the element x at position i in the list s. Further elements must be shifted to the right.
s.add(i, x)
45
Sleep for 5 seconds in current thread, before proceeding with the next instructions.
Thread.sleep(5000L)
46
Create the string t consisting of the 5 first characters of the string s.
Make sure that multibyte characters are properly handled.
val t = s.take(5)
47
Create string t consisting in the 5 last characters of string s.
Make sure that multibyte characters are properly handled.
val t = s.takeLast(5)
48
Assign to variable s a string literal consisting in several lines of text, including newlines.
val s =
    """
    This is my
    multi-line string.
    """
49
Build list chunks consisting in substrings of the string s, separated by one or more space characters.
val chunks = s.split("\\s+".toRegex())
50
Write a loop that has no end clause.
while (true) { }
51
Determine whether the map m contains an entry for the key k
m.containsKey(k)
52
Determine whether the map m contains an entry with the value v, for some key.
m.containsValue(v)
53
Concatenate elements of string list x joined by the separator ", " to create a single string y.
val y = listOf(x).joinToString(", ")
54
Calculate the sum s of the integer list or array x.
val numbers = listOf(1, 2, 3, 4)
val sum = numbers.sum()
55
Create the string representation s (in radix 10) of the integer value i.
val s = i.toString()
56
Fork-join : launch the concurrent execution of procedure f with parameter i from 1 to 1000.
Tasks are independent and f(i) doesn't return any value.
Tasks need not run all at the same time, so you may use a pool.
Wait for the completion of the 1000 tasks and then print "Finished".
(1..1000)
    .map { i ->
        CoroutineScope(Dispatchers.Default).async {
            f(i)
        }
    }
    .awaitAll()
print("Finished")
57
Create the list y containing the items from the list x that satisfy the predicate p. Respect the original ordering. Don't modify x in-place.
val y = x.filter(p)
58
Create the string lines from the content of the file with filename f.
File(f).readText()
59
Print the message "x is negative" to standard error (stderr), with integer x value substitution (e.g. "-2 is negative").
System.err.println("$x is negative")
69
Use seed s to initialize a random generator.

If s is constant, the generator output will be the same each time the program runs. If s is based on the current value of the system clock, the generator output will be different each time.
val random = Random(seed=s)
71
Basic implementation of the Echo program: Print all arguments except the program name, separated by space, followed by newline.
The idiom demonstrates how to skip the first argument if necessary, concatenate arguments as strings, append newline and print it to stdout.
fun main(args: Array<String>) = args.forEach(::println)
87
Exit immediately.
If some extra cleanup work is executed by the program runtime (not by the OS itself), describe it.
exitProcess(0)
94
Print the name of the type of x. Explain if it is a static type or dynamic type.

This may not make sense in all languages.
println(x::class.simpleName)
96
Set the boolean b to true if string s starts with prefix prefix, false otherwise.
val b = s.startsWith(prefix)
97
Set boolean b to true if string s ends with string suffix, false otherwise.
b = s.endsWith(suffix)
100
Sort elements of array-like collection items, using a comparator c.
items.sortWith(c)
110
Set the boolean blank to true if the string s is empty, or null, or contains only whitespace ; false otherwise.
val blank = s.isNullOrBlank()
117
Set n to the number of elements of the list x.
val n = x.size
119
Remove duplicates from the list x.
Explain if the original order is preserved.
x = x.toSet().toList()
Alternative implementation:
x = x.distinct()
126
Write a function foo that returns a string and a boolean value.
fun foo() : Pair<String, Boolean> = Pair(5, true)

fun useFoo() {
  val a, b = foo()
}
131
Execute f1 if condition c1 is true, or else f2 if condition c2 is true, or else f3 if condition c3 is true.
Don't evaluate a condition when a previous condition was true.
when {
  c1 -> f1()
  c2 -> f2()
  c3 -> f3()
}
134
Declare and initialize a new list items, containing 3 elements a, b, c.
val items = listOf(a, b, c)
137
Set the boolean b to true if the string s contains only characters in the range '0'..'9', false otherwise.
val regex = Regex("[0-9]*")
val b = regex.matches(s)
Alternative implementation:
fun String?.isOnlyDigits() = !this.isNullOrEmpty() && this.all { Character.isDigit(it) }
144
Set boolean b to true if file at path fp exists on filesystem; false otherwise.

Beware that you should not do this and then in the next instruction assume the result is still valid, this is a race condition on any multitasking OS.
b = File(fb).exists()
152
Create string s containing only the character c.
val s: String = c.toString()
157
Initialize a constant planet with string value "Earth".
val planet = "Earth"
165
Assign to the variable x the last element of the list items.
var x = items.last()
166
Create the list ab containing all the elements of the list a, followed by all the elements of the list b.
val ab = a + b
169
Assign to the integer n the number of characters of the string s.
Make sure that multibyte characters are properly handled.
n can be different from the number of bytes of s.
val n = s.length
179
Return the center c of the rectangle with coördinates(x1,y1,x2,y2)
fun center(x1: int, y1: int, x2: int, y2: int) = Pair((x1 + x2)/2, (y1 + y2)/2)
Alternative implementation:
data class Point(val x: Double, val y: Double)
data class Rectangle(val x1: Double, val y1: Double, val x2: Double, val y2: Double){
  fun center() = Point( x = (x1 + x2)/2, y =(y1 + y2)/2)
}
184
Assign to t a string representing the day, month and year of the day after the current date.
val t = LocalDate.now().plusDays(1).toString()
186
Exit a program cleanly indicating no error to OS
exitProcess(0)
196
Given an integer array a of size n, pass the first, third, fifth and seventh, ... up to the m th element to a routine foo which sets all these elements to 42.
fun foo(a : IntArray, idx: IntProgression) = 
  idx.forEach{ a[it] = 42 }
foo(a, 0 .. (m-1) step 2)
197
Retrieve the contents of file at path into a list of strings lines, in which each element is a line of the file.
val lines = File(path).readLines()
205
Read an environment variable with the name "FOO" and assign it to the string variable foo. If it does not exist or if the system does not support environment variables, assign a value of "none".
val foo = System.getenv("FOO") ?: "none"
220
Create t consisting of 3 values having different types.

Explain if the elements of t are strongly typed or not.
val t = Triple(2.5, "foo", true)
223
Loop through list items checking a condition. Do something else if no matches are found.

A typical use case is looping through a series of containers looking for one that matches a condition. If found, an item is inserted; otherwise, a new container is created.

These are mostly used as an inner nested loop, and in a location where refactoring inner logic into a separate function reduces clarity.
items.find { it == "baz" }
  ?.let { println("found it") }
  ?: println("never found it")
Alternative implementation:
if(items.any { it == "baz" })
  println("found it")
else 
  println("never found it")
235
Assign to byte array data the bytes represented by the base64 string s, as specified by RFC 4648.
String(Base64.getDecoder().decode(s))
246
Set c to the number of distinct elements in the list items.
val c = items.distinct().size
249
Define variables a, b and c in a concise way.
Explain if they need to have the same type.
val (a, b, c) = listOf("A", "B", "C")
252
Assign to the variable x the string value "a" if calling the function condition returns true, or the value "b" otherwise.
val x = if(condition()) "a" else "b"
266
Assign to the string s the value of the string v repeated n times, and write it out.

E.g. v="abc", n=5 ⇒ s="abcabcabcabcabc"
val s = v.repeat(n)
println(s)
269
Given the enumerated type t with 3 possible values: bike, car, horse.
Set the enum value e to one of the allowed values of t.
Set the string s to hold the string representation of e (so, not the ordinal value).
Print s.
val e = T.BIKE
val s = e.name
println(s)
286
Print a line "Char i is c" for each character c of the string s, where i is the character index of c in s (not the byte index).

Make sure that multi-byte characters are properly handled, and count for a single character.
s.forEachIndexed { i, c ->
  println("Char $i is $c")
}
289
Create the string s by concatenating the strings a and b.
val s = a + b
302
Given the integer x = 8, assign to the string s the value "Our sun has 8 planets", where the number 8 was evaluated from x.
val s = "Our sun has $x planets"