Part of Github Copilot with Kotlin

Kotlin with Copilot: Create a lambda function to square a number

Sandy LaneSandy Lane

Video: Kotlin with Copilot: Create a lambda function to square a number by Taught by Celeste AI - AI Coding Coach

Take the quiz on the full lesson page
Test what you've read · interactive walkthrough

Kotlin: Lambda to Square a Number

val square: (Int) -> Int = { it * it }. The single-arg sibling of episode 30. Demonstrates how it shines in tiny lambdas.

A small puzzle that combines episode 29 (one-line lambda) with the squaring operation. The shortest possible useful lambda.

The Copilot prompt

fun main() {
  // Lambda that squares an integer
  val square: (Int) -> Int =

Copilot generates:

val square: (Int) -> Int = { number -> number * number }

println(square(5))    // 25
println(square(10))   // 100

The compact form

val square: (Int) -> Int = { it * it }

it makes the lambda 12 characters shorter. For a one-character operation like this, the shorter form is clearly better.

Versus pow()

import kotlin.math.pow

val square: (Int) -> Int = { (it.toDouble().pow(2)).toInt() }

pow(2) works but converts to Double and back. For squaring (* itself), multiplication is faster and exact.

For higher powers, pow is right:

val cube: (Int) -> Int = { (it.toDouble().pow(3)).toInt() }
val tenth: (Int) -> Double = { it.toDouble().pow(10) }

Squaring a list

val numbers = listOf(1, 2, 3, 4, 5)
val squares = numbers.map { it * it }
println(squares)   // [1, 4, 9, 16, 25]

map { it * it } is the canonical "transform each element" — produces a new list of the same size with each element squared.

Sum of squares

val numbers = (1..10).toList()
val sumOfSquares = numbers.sumOf { it * it }
println(sumOfSquares)   // 385

sumOf { selector } maps + sums in one pass. Faster than numbers.map { it * it }.sum() because it skips the intermediate list.

For 1..N, the closed form is N * (N + 1) * (2N + 1) / 6:

fun sumOfSquares(n: Int): Long = n.toLong() * (n + 1) * (2 * n + 1) / 6
println(sumOfSquares(10))   // 385

For huge N, the closed form is O(1) — far better than the O(n) loop.

Using the lambda as a function ref

fun square(n: Int): Int = n * n

val numbers = listOf(1, 2, 3, 4, 5)
val squares = numbers.map(::square)

When the operation has a name, function reference (::square) is even cleaner than the lambda.

Building a "powers of n" function

fun makePower(exp: Int): (Int) -> Long = { base ->
  var result = 1L
  repeat(exp) { result *= base }
  result
}

val square = makePower(2)
val cube = makePower(3)

println(square(5))   // 25
println(cube(5))     // 125

makePower returns a closure. Each call gets its own exp. Same factory pattern from episode 25.

For pow/sqrt-shaped math, just use the stdlib directly. The factory is more useful for operations like discount calculators, currency converters, etc.

Squaring with metaprogramming

You don't need this, but for the curious — Kotlin's operator functions let you define **:

infix fun Int.power(exp: Int): Int {
  var result = 1
  repeat(exp) { result *= this }
  return result
}

println(5 power 2)   // 25 — infix
println(5.power(3))  // 125

infix lets the function be called without dots: 5 power 2. Can't actually create ** (Kotlin doesn't support custom operator symbols), but infix gets close.

Common mistakes

Using pow(2) for squares. Slower; converts through Double.

Forgetting it. { * 2 } doesn't compile. Need { it * 2 }.

Squaring large numbers without Long. (100_000).let { it * it } overflows Int (it would be 10 billion). Use Long for any "could be > 46,000" multiplication.

pow(2) on Int. Doesn't exist directly — Int.toDouble().pow(2).toInt() is the path. For multiplication, just it * it.

Confusing ^ with power. Kotlin's ^ is XOR, not exponent. 5 ^ 2 is 7, not 25. Use * or pow.

What's next

Episode 32: Convert a list of numbers to a comma-separated string. joinToString(", ") — one line.

Recap

val square: (Int) -> Int = { it * it }. Multiplication is faster than pow(2). For lists, map { it * it } produces squared values; sumOf { it * it } sums them in one pass. For Int.power(exp), write a helper function or use pow after converting to Double. For huge ranges, prefer closed-form math (n(n+1)(2n+1)/6 for sum of 1..N squares).

Next episode: list to string.

Ready? Take the quiz on the full lesson page →
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.