Reputation: 3297
I have created a case class like this:
case class MyClass[T](attName: String, getter: (ResultSet) => T)
I intantiate two exemple like this:
val ex1 = MyClass("name", (rs: ResultSet) => rs.getString("name"))
val ex2 = MyClass("age", (rs: ResultSet) => rs.getInt("age"))
I would like to avoid to use two time name and age for each line. Do you have any idea to reuse attName in the second attribute? Thank
Upvotes: 0
Views: 57
Reputation: 40508
Something like this maybe:
class MyClass[T](name: String, getter: (ResultSet, String) => T) {
def getIt(rs: ResultSet): T = getter(rs, name)
}
case object MyClassName extends MyClass[String]("name", _ getString _)
case object MyClassAge extends MyClass[Int]("age", _ getInt _)
Or just
val ex1 = new MyClass("name", _ getString _)
val ex2 = new MyClass("age", _ getInt _)
Upvotes: 1
Reputation: 2453
Two choices:
Create an object to hold the static things like column names and use them as variables:
object MyClass {
object DbKeys {
val name = "name"
val age = "age"
}
}
case class MyClass[T](attName: String, getter: (ResultSet) => T)
val ex1 = MyClass(DbKeys.name, (rs: ResultSet) => rs.getString(DbKeys.name))
val ex2 = MyClass(DbKeys.age, (rs: ResultSet) => rs.getInt(DbKeys.age))
Still with the object but this time with an abstract class and 2 case classes. Notice that when instanciating you don't specify column names.
object MyClassArg {
object DbKeys {
val name = "name"
val age = "age"
}
}
abstract class MyClassArg[T](attName: String, getter: (ResultSet) => T)
case class MyClassName() extends MyClassArg(DbKeys.name, (rs: ResultSet) => rs.getString(DbKeys.name))
case class MyClassAge() extends MyClassArg(DbKeys.age, (rs: ResultSet) => rs.getString(DbKeys.age))
val ex1 = MyClassName
val ex2 = MyClassAge
I prefer the second choice because it makes for a cleaner use. You can make MyClassArg
non abstract to allow more flexibility.
The getter
can also be further abstracted to avoid repeating the rs.getString
part.
Upvotes: 1