Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

scala - How to override variable studentName given in class within changeName variable and new variable is used in userName when I call changeName method?

class Person {
  val studentName = "Arpana"

  def changeName(id:String, name:String) ={
  val studentName = name
  useName(id)
  }
  def useName(id:String) = {
    println(s"use name is $id, by $studentName")
  }
}

object Person {
  def main(args: Array[String]): Unit = {
    (new Person).changeName("2", "Shubham")
  }
}

I don't want to use var in code, can we do it by keywords, I tried with keywords like super, protected, private, final but didn't work. In actual I want to apply this in the below code.

abstract class BaseRepository[T <: BaseModel : ClassTag : StriveSerializer] {
  self: BaseConnection =>
  val tableName: String = implicitly[ClassTag[T]].runtimeClass.getSimpleName
  private val serializer = implicitly[StriveSerializer[T]]
  private def executeInserts(query: String): Future[Boolean] = Future {
    val preparedStatement = self.connection.prepareStatement(query)
    preparedStatement.execute()
  }
  def exist(id: String, name: String): Future[Boolean] = {
    val tableName = name
    val promise = Promise[Boolean]
    queryById(id).onComplete {
      case Success(_) => promise.success(true)
      case Failure(ex) => promise.failure(ex)
    }
    promise.future
  }

  def queryById(id: String): Future[T] = {
    val getSql = s"SELECT * FROM $tableName WHERE id == $id;"
    executeReads(getSql).map(serializer.fromResultSet)
  }
}

I want when i call exist function then table name given in exist function override in queryById method table name .

question from:https://stackoverflow.com/questions/65841703/how-to-override-variable-studentname-given-in-class-within-changename-variable-a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems like a bit of mix of Java and Scala style. I tried to refactor a bit assuming the intention behind the code. Try and see if this achieves what you want to do:

class Person(_id: String, _studentName: String) {
  private val id: String = _id
  private val studentName: String = _studentName

  def useName() = {
    println(s"use name is $id, by $studentName")
  }
}

object Person extends App {
  new Person("2", "Shubham").useName()
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...