Chapter 9: Functions – Part 2 (Advanced)

Functions – Part 2 (Advanced) — this is where Kotlin functions become really powerful, elegant, and very professional! ☕✨

We’re going to cover four super-important advanced function features that you will see everywhere in real Kotlin code (Android apps, backend services, libraries, etc.):

  1. Variable number of arguments (vararg)
  2. Infix functions (super clean syntax!)
  3. Local functions (functions inside functions)
  4. Tail-recursive functions (tailrec) (Kotlin’s safe recursion)

As always, imagine we’re sitting together in a quiet Mumbai café — I’ll explain everything very slowly, with real-life analogies, complete runnable examples, step-by-step breakdowns, tables, common mistakes with fixes, and fun facts so everything sticks perfectly.

Let’s dive in!

1. Variable Number of Arguments – vararg

vararg allows a function to accept any number of arguments of the same type — like print() or listOf().

Syntax: Put vararg before the parameter name.

Kotlin

Calling it

Kotlin

Output:

text

Inside the function → names is treated as an array (Array<String>)

Very common pattern – combine with other parameters

Kotlin

Important rule:

  • vararg parameter should be last (or only one vararg allowed)
  • Wrong: fun wrong(vararg a: Int, b: String) → compile error
  • Correct: fun correct(b: String, vararg a: Int)

2. Infix Functions – Super Clean & Readable Syntax

Infix functions let you call a function without the dot and parentheses — like operators!

Rules to make a function infix:

  1. Must be a member function or extension function
  2. Must have exactly one parameter
  3. Must be marked with infix keyword

Real-life analogy: Normal: person.addFriend(friend) Infix: person addFriend friend → looks like natural language!

Example 1 – Custom infix operator

Kotlin

Output:

text

Example 2 – Infix with numbers (real-world style)

Kotlin

Very common built-in infix functions:

  • to → 1 to 10
  • downTo → 10 downTo 1
  • step → 1..10 step 2
  • until → 1 until 10

3. Local Functions – Functions Inside Functions

You can declare functions inside other functions — very useful for helper logic that you don’t want to expose outside.

Real-life analogy: You’re cooking biryani → you have a main function (cookBiryani) Inside it, you have small helper functions (fryOnions, marinateChicken) that only make sense inside this recipe.

Example

Kotlin

Output:

text

Very common use: inside complex functions to break logic into small readable pieces.

4. Tail-Recursive Functions (tailrec) – Safe Recursion

Recursion in Kotlin is safe only if it’s tail-recursive — otherwise you get StackOverflowError for deep recursion.

tailrec keyword tells compiler: optimize this recursion into a loop (no stack growth!)

Example – Factorial (normal recursion vs tail-recursive)

Bad (can crash for large n):

Kotlin

Good (tail-recursive – safe & fast):

Kotlin

When can you use tailrec?

  • The recursive call must be the last thing the function does
  • No other work after the recursive call

Real-world use: tree traversal, list processing, etc.

Quick Recap Table (Your Cheat Sheet)

Feature Kotlin Way (Best Practice) Example / Key Point
vararg fun greet(vararg names: String) Accepts any number of arguments
Infix function infix fun addFriend(friend: Person) Call without . & () → p addFriend f
Local function fun outer() { fun inner() { … } } Helper function visible only inside outer
Tail-recursive tailrec fun factorial(n: Int, acc: Long = 1) Safe recursion – compiler turns into loop

Common Newbie Mistakes & Fixes

Mistake Problem Fix
Putting vararg not as last parameter Compile error vararg must be the last parameter
Forgetting infix keyword Cannot use infix call Add infix before fun
Using return inside local function Returns from outer function Use return@label if needed
Adding code after recursive call tailrec not allowed Make sure recursive call is the last action
Not marking tail-recursive functions StackOverflowError for large input Add tailrec keyword

Homework for You (Let’s Make It Fun!)

  1. Basic Create a function fun printAll(vararg messages: String) that prints all messages with numbers (1. Hello, 2. World…)
  2. Medium Create an infix function infix fun Person.likes(food: String) → prints “$name likes $food!”
  3. Advanced Write a tail-recursive function tailrec fun sum(n: Int, acc: Long = 0) that sums numbers from 1 to n.
  4. Fun Create a function fun makeSandwich(vararg ingredients: String) → prints a nice sandwich description.
  5. Challenge Fix this code so it works safely for large input:
    Kotlin

You’ve just unlocked Kotlin’s most powerful function features — now your code is clean, expressive, and safe!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *