# Calculator algorythm - Error

#### System32

##### New member
I found this code on the internet:

Code:
``````private fun evaluateExpression(expression: String): Int {
val precedence = mapOf('+' to 1, '-' to 1, '*' to 2, '/' to 2)

fun applyOperator(operator: Char, operand2: Int, operand1: Int): Int {
return when (operator) {
'+' -> operand1 + operand2
'-' -> operand1 - operand2
'x' -> operand1 * operand2
'/' -> operand1 / operand2
else -> throw IllegalArgumentException("Invalid operator: \$operator")
}
}

val stack = mutableListOf<Int>()
var i = 0
while (i < expression.length) {
if (expression[i].isDigit()) {
var j = i
while (j < expression.length && expression[j].isDigit()) {
j++
}
val num = expression.substring(i, j).toInt()
i = j
} else if (expression[i] in precedence.keys) {
while (stack.isNotEmpty() && !stack.last().equals('(') && precedence[expression[i]]!! <= precedence[stack.last()]!!) {
val operand2 = stack.removeAt(stack.lastIndex)
val operand1 = stack.removeAt(stack.lastIndex)
val operator = stack.removeAt(stack.lastIndex)
val result = applyOperator(operator.toChar(), operand2, operand1)
}
i++
} else if (expression[i] == '(') {
i++
} else if (expression[i] == ')') {
while (stack.isNotEmpty() && !stack.last().equals('(')) {
val operand2 = stack.removeAt(stack.lastIndex)
val operand1 = stack.removeAt(stack.lastIndex)
val operator = stack.removeAt(stack.lastIndex)
val result = applyOperator(operator.toChar(), operand2, operand1)
}
stack.removeAt(stack.lastIndex) // Remove the opening parenthesis
i++
} else {
i++
}
}

while (stack.size > 1) {
val operand2 = stack.removeAt(stack.lastIndex)
val operand1 = stack.removeAt(stack.lastIndex)
val operator = stack.removeAt(stack.lastIndex)
val result = applyOperator(operator.toChar(), operand2, operand1)
}

return stack.first()
}``````

Now, the error I am getting here is: Type inference failed. The value of the type parameter K should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly.

It is related to this part of the code: I have no idea how to solve this issue. I noticed that in Android studio with Kotlin, when you use last, it doesn't really work neatly.

Replies
1
Views
293
A
Replies
2
Views
1K
A
Replies
1
Views
1K
Replies
1
Views
872
Replies
2
Views
4K