Yuseff
Yuseff

Reputation: 319

assignments are not expressions, and only expressions are allowed in this context --- how to resolve this error

I am trying to find the find the result of num1 raised to the power num2: This is my code ->

 fun power(num1 : Int, num2: Int): Int {
      var result = 1
      while (num2 != 0) {
       return  result *= num1
       num2--
      }
    } 

But the above code is producing the following error -->

Calculator.kt:30:16: error: assignments are not expressions, and only expressions are allowed in this context
       return  result *= num1
               ^
Calculator.kt:33:5: error: a 'return' expression required in a function with a block body ('{...}')
    } 
    ^

I have read a number of articles but not able to understand. Any help will be highly appreciated. Thank you

Upvotes: 1

Views: 2408

Answers (2)

Tenfour04
Tenfour04

Reputation: 93581

An expression is something that evaluates to a value. An assignment is something that assigns a value to a variable or property.

x *= y is an assignment that is shorthand for x = x * y.

You cannot return an assignment, because it does not evaluate to a value. An assignment contains an expression on the right side of the equals sign, but as a whole does not represent an expression.

There are some other syntax problems you have. You can't modify a function paramter's value (num2-- isn't allowed).

The logic also doesn't make sense. return returns an expression immediately. To fix your code, you need to create a local variable from num2, and move the return statement to the end.

fun power(num1 : Int, num2: Int): Int {
    var result = 1
    var count = num2
    while (count != 0) {
        result *= num1
        count--
    }
    return result
}

FYI, there's a function called repeat that is simpler than using a while loop with a counter. It runs the code inside the brackets by the number of times you give.

fun power(num1 : Int, num2: Int): Int {
    var result = 1
    repeat(num2) {
        result *= num1
    }
    return result
}

Upvotes: 4

Andrea Nisticò
Andrea Nisticò

Reputation: 516

You function contains multiple errors, I suggest you to study Kotlin, here a reference. Kotlin website has some more material.

Back to your problem, I have modified your function:

fun power(num1 : Int, num2: Int): Int {
  var result = 1
  var num2_local = num2
  while (num2_local != 0) {
   result *= num1
   num2_local--
  }
  return result
} 

Problems with your version:

  • you return from the function immediately
  • basic types args passed to kotlin functions are passed by const copy, this means that you cannot modify them (e.g num2--)

If you keep a local modifiable reference (var keyword) withing your function, then you achieve your goal

Upvotes: 1

Related Questions