Calculator

Report a typo

You have four functions: add, subtract, multiply, and divide:

fun add(x: Int, y: Int) = x + y

fun subtract(x: Int, y: Int) = x - y

fun multiply(x: Int, y: Int) = x * y

fun divide(x: Int, y: Int) = x / y

In this task, you should create a calculator by using function references of these four functions.

As input, you are given two numbers and the name of the action you should perform on the numbers. You need to output the result.

The action names can be: add, subtract, multiply, or divide.

Guaranteed that y can't be 0 when the action is divide.

Sample Input 1:

3
2
multiply

Sample Output 1:

6
Write a program in Kotlin
fun add(x: Int, y: Int) = x + y

fun subtract(x: Int, y: Int) = x - y

fun divide(x: Int, y: Int) = x / y

fun multiply(x: Int, y: Int) = x * y

fun calculate(x: Int, y: Int, operator: (Int, Int) -> Int) {
// write your code here
val result = ...
print(result)
}

fun main() {
val x: Int = readLine()!!.toInt()
val y: Int = readLine()!!.toInt()
val operator: String = readLine()!!
when (operator) {
// write your code here
"add" -> calculate(...)
"subtract" -> calculate(...)
"multiply" -> calculate(...)
"divide" -> calculate(...)
}
}
___

Create a free account to access the full topic