kotlin: How to write a Consumer

November 10, 2019

The software used for this howto is Kotlin 1.3.50.

fun normalize(fields: Map): Gig {

  val err = { x : String -> throw IllegalStateException("no '$x' in $fields") }
  val parsed = ParsedFields(
          fields["date"] ?: err("date"),
          fields["time"] ?: err("time"),
          fields["detailURL"] ?: ""

Here err has the type (String) -> Nothing and is equivalent to a Java 8 java.util.function.Consumer.

Kotlin does away with the ceremony of Function, BiFunction, Consumer, Supplier, etc., etc. and calls them all functions.

For completeness of this example, ParsedFields is a data class with three non-null fields, as below. The normalize method throws an exception if either of the first two are missing and defaults the third to the empty string if it is missing.

data class ParsedFields(
  val date : String,
  val time : String,
  val detailURL : String