Is there any way to use two Any type variables to perform addition/subtraction/multiplication/subtraction? The two Any types can be either Int or Float, and they may or may not be the same type (So one could be Int and the other one Float, or they could both be Int or Float).
Part of my code:
// this.visit() returns Any?
// node.left and node.right can be Int or Float, and they may or may not be the same type
when (node.op.type) {
TokenType.PLUS -> return this.visit(node.left) this.visit(node.right)
TokenType.MINUS -> return this.visit(node.left) - this.visit(node.right)
TokenType.MUL -> return this.visit(node.left) * this.visit(node.right)
TokenType.DIV -> return this.visit(node.left) / this.visit(node.right)
}
With this code it doesn't compile and outputs Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
followed by a long list of types supported by the operator.
CodePudding user response:
Can you make the node type Number
instead of Any
? Then you could use toFloat()
on the returned items to be able to perform arithmetic with them.
val left = visit(node.left).toFloat()
val right = visit(node.right).toFloat()
return when (node.op.type) {
TokenType.PLUS -> left right
TokenType.MINUS -> left - right
TokenType.MUL -> left * right
TokenType.DIV -> left / right
}
I just noticed you said the return value is nullable, so you need to decide what to return in the case there is no left or right value...
val left = visit(node.left)?.toFloat()
val right = visit(node.right)?.toFloat()
if (left == null || right == null) {
//...
//return ...
}
return when (node.op.type) {
TokenType.PLUS -> left right
TokenType.MINUS -> left - right
TokenType.MUL -> left * right
TokenType.DIV -> left / right
}
If you have to keep the node type as Any, you can cast them to Number before using toFloat()
, but if it's possible they are not numbers, you will have to use safe casts and decide what to do with non-numbers.
CodePudding user response:
Simplest way will be to convert both to float and do the operations and return accordingly , like :
(8f).toFloat() (10L).toFloat()