Def Inside Def, a Scala language concept

Last updated

A great aspect of Scala is being able to declare functions inside functions, making it possible to reduce repetition.

def exampleDef(input: String): String = {
  def surroundInputWith(char: Char): String = s"$char$input$char"
  surroundInputWith('-')
}

assert(exampleDef("test") == "-test-")

It is also frequently used in combination with Tail Recursion.