skhprabu
skhprabu

Reputation: 73

Scala : Type Mismatch

I'm new to scala. Here is my code Snippet

  var test_Id:Int = 0
  def getTestID():Int = {
  synchronized {
  return test_Id = test_Id+1
    }

This give me a compilation error

type mismatch;  found   : Unit  required: Int   HelloWorld.scala

I'm defining test_Id as Int. But when i try to return that, it is not identified as Int. How should I return this as Int

Upvotes: 2

Views: 118

Answers (2)

Ajit Lakhwani
Ajit Lakhwani

Reputation: 24

In Scala every statement is expression that yields a value. Whatever expression is evaluated at last line in method would be returned. Assignment operation is evaluated as type Unit. So you need to separate assignment expression from return value expression.

  var test_Id:Int = 0
  def getTestID():Int = {
  synchronized {
      test_Id = test_Id+1
      test_Id // return keyword is optional.
  }

Upvotes: 0

Lee
Lee

Reputation: 144136

Assignment has type Unit so you need to separate the update from the read:

def getTestID() : Int = {
  synchronized {
      test_Id = test_Id+1
      test_Id
  }
}

Upvotes: 4

Related Questions