0
0
Kotlinprogramming~15 mins

Infix functions for readable calls in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Infix functions for readable calls
📖 Scenario: Imagine you are building a simple calculator app that can add numbers in a way that reads like a sentence. You want to make your code easy to read and understand, just like a natural language sentence.
🎯 Goal: You will create an infix function in Kotlin to add two numbers with a readable call style, then use it to add two numbers and print the result.
📋 What You'll Learn
Create a class called Calculator with a property value of type Int
Add an infix function called add inside Calculator that takes another Calculator and returns a new Calculator with the sum of the two values
Create two Calculator objects with values 10 and 5
Use the add function in infix style to add the two objects
Print the value of the result
💡 Why This Matters
🌍 Real World
Infix functions make code easier to read, like writing sentences. This helps when building apps that do calculations or combine data.
💼 Career
Understanding infix functions is useful for Kotlin developers to write clean, readable code in Android apps and backend services.
Progress0 / 4 steps
1
Create the Calculator class with a value property
Create a class called Calculator with a property value of type Int. Initialize it using the primary constructor.
Kotlin
Need a hint?
Use Kotlin's primary constructor syntax to create the class with a property.
2
Add an infix add function to Calculator
Inside the Calculator class, add an infix function called add that takes another Calculator as a parameter named other. It should return a new Calculator with the sum of this.value and other.value.
Kotlin
Need a hint?
Use the keyword 'infix' before the function and return a new Calculator with summed values.
3
Create two Calculator objects and add them using infix
Create two Calculator objects named calc1 with value 10 and calc2 with value 5. Then create a new Calculator called result by adding calc1 and calc2 using the infix add function.
Kotlin
Need a hint?
Create objects with the given values and use the infix function without dot or parentheses.
4
Print the value of the result
Write a println statement to print the value property of the result object.
Kotlin
Need a hint?
Use println(result.value) to show the sum.