HelloCW
HelloCW

Reputation: 2325

Which one does _id point when I use it at a function in Kotlin?

A: Code A is clear, _myid in whereSimple("$_myid = ? ",_id.toString()) means val _myid:String=DBRecordTable._ID

B: I confuse Code B, which one does _id in whereSimple("$_id = ? ",_id.toString()) mean, is it val _id:String=DBRecordTable._ID ? or is it fun getRecordByID(_id:Long) ?

BTW, Code C is wrong, it can't be compiled!

Code A

class DBRecordHandler(val mDBRecordHelper: DBRecordHelper =DBRecordHelper.instance,
                      val tableName:String =DBRecordTable.TableNAME,
                      val _myid:String=DBRecordTable._ID
                      ) {


      fun getRecordByID(_id:Long):MDBRecord? = mDBRecordHelper.use{
          select(tableName)
              .whereSimple("$_myid = ? ",_id.toString())
              .parseOpt{MDBRecord(HashMap(it)) }
      }
}

Code B

class DBRecordHandler(val mDBRecordHelper: DBRecordHelper =DBRecordHelper.instance,
                      val tableName:String =DBRecordTable.TableNAME,
                      val _id:String=DBRecordTable._ID
                      ) {


      fun getRecordByID(_id:Long):MDBRecord? = mDBRecordHelper.use{
          select(tableName)
              .whereSimple("$_id = ? ",_id.toString())
              .parseOpt{MDBRecord(HashMap(it)) }
      }
}

Code C

class DBRecordHandler(val mDBRecordHelper: DBRecordHelper =DBRecordHelper.instance,
                      val tableName:String =DBRecordTable.TableNAME,
                      val _id:String=DBRecordTable._ID
                      ) {


      fun getRecordByID(_id:Long):MDBRecord? = mDBRecordHelper.use{
          select(tableName)
              .whereSimple("${this._id}= ? ",_id.toString())
              .parseOpt{MDBRecord(HashMap(it)) }
      }

}

Upvotes: 0

Views: 58

Answers (1)

Yoni Gibbs
Yoni Gibbs

Reputation: 7026

The "more local" version of the variable is the one that will be used, i.e. the one declared as a parameter into the function, rather than the one declared as a constructor parameter of the class. This is called shadowing.

Note that if you ctrl+click on the variable in your code, your IDE will take you to its declaration, so you can see which instance is going to be used at any point in the code where you refer to it.

Upvotes: 1

Related Questions