Automator
Automator

Reputation: 53

Scala Increment Counter on calling Function

How to increment a function each time its called in scala? I have a function A which performs a set of actions, when a user calls the function A, i would like to have a counter which increments and returns the counter value. The below code doesnt return the expected counter of 1 when i call it.

def return_id (email_user: String) : Int = {
    Thread.sleep(1000)
    val count = 0
    implicit val conn = ExecuteQuery.getConnection(GENERAL_DB, DB_USER, DB_PASS)
    var idQuery=executeQuery(s"SELECT id FROM Profile WHERE email = '$email_user';")
    idQuery.first()
    val pid=idQuery.getInt("id")
    println(pid)
    if(pid != 0){
     +count = 1
    }
    return count
   }

Upvotes: 2

Views: 6178

Answers (2)

mavarazy
mavarazy

Reputation: 7735

The way this code is written, it would not work correctly - your counter is inside a function and get's created and disposed on each function call, so it would always return constant value.

You need to have your counter defined outside your function block

  1. One possible way to do it, using AtomicInteger

    val count = new AtomicInteger()
    
    def return_id (email_user: String) : Int = {
        Thread.sleep(1000)
        implicit val conn = ExecuteQuery.getConnection(GENERAL_DB, DB_USER, DB_PASS)
        var idQuery=executeQuery(s"SELECT id FROM Profile WHERE email = '$email_user';")
        idQuery.first()
        val pid = idQuery.getInt("id")
        println(pid)
        if(pid != 0){
           count.incrementAndGet()
        } else {
           count.get()
        }
    }
    

count is an AtomicInteger, to handle concurrent access.

  1. The other option, more Scala way, is to have an Actor, that would handle counting for you, with 2 commands increase and get.

And many others.

Upvotes: 1

Justin Pihony
Justin Pihony

Reputation: 67115

In Scala, a val is an immutable object and cannot be changed, whereas var is a variable object that CAN change. So, you can make this work by using a var and doing count = count + 1. Although the rest of the code is highly suspect, and I hope this is just a toy that you are playing with....but that is a direct answer.

Upvotes: 1

Related Questions