Project design
- Kotlin course
- Beginner
- Lesson 19/116
- 6 min
Design the structure of the calculator project and write the skeleton code.
Project: Calculator
In this 5-lesson project you'll build a calculator. Each lesson adds one piece, and by the final lesson you'll have a complete app.
You'll use:
fun main()and top-level functionsadd,subtract,multiply,dividefunctionsiffor zero checkstry/catchfor error handling- A
forloop for repetition
Ready? Let's start.
File design
We'll put the calculator in a single .kt file. The file holds both the calculation functions and fun main(). The calculation functions are top-level, so they can be called directly as add(5, 3) without creating an object.
Each function returns Int because it produces an integer result. Parameters are also Int.
fun add(a: Int, b: Int): Int {
return a + b
}
fun main() {
println(add(5, 3))
}Practice Write the first skeleton
Write a fun main(). Print Calculator with println.
Sample solution
fun main() {
println("Calculator")
}Expected output
Calculator
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a calculator do?
- Saves a file
- Queries a database
- Takes two numbers and performs an operation Correct answer
- Declares a class
Explanation: A calculator takes two numbers and performs an operation.
2 Complete the function signature
fun add(a: Int, b: Int): ____ { return a + b }
fun add(a: Int, b: Int): Int { return a + b }
Explanation: The add function returns Int.
3 Match the project stages
| Term | Meaning |
|---|---|
main |
Entry point |
add |
Addition |
subtract |
Subtraction |
println |
Output |