I found this code on the internet:
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.
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()
stack.add(num)
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)
stack.add(result)
}
stack.add(expression[i].toString().toInt())
i++
} else if (expression[i] == '(') {
stack.add(expression[i].toString().toInt())
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.add(result)
}
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)
stack.add(result)
}
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.