1

私はscalaにかなり慣れていません。一種の動的リポジトリを作成しようとしました。単純なケースクラスの属性を読み取るにはどうすればよいですか?

trait Repository[T <:MetaEntity] {

    persist(entity:T) : Boolean {
        // TO BE IMPLEMENTED

        // Pseudo code:
        for (attribute <- getAttributes()) {
           // Flatten properies to one string...
           // Primitives can be converted with attribute.value.toString ?
           // Type: attribute.type ?
           // Object references should be coverted to object.id.toString ?
        } 
    }   

}

abstarct class MetaEntity {}

case class SimpleEntity(id: Int, name: String, version: Int) extends MetaEntity {
}

case class ComplexEntity(id: Int, name: String, simpleChild: SimpleEntity) extends MetaEntity{}

object ComplexEntityRepository extends Repository[ComplexEntity] {}
object SimpleEntityRepository extends Repository[SimpleEntity] {}
4

2 に答える 2

1

ScalaのケースクラスはProductを拡張します(ここを参照)。たぶん、次のコードが役に立ちます(REPLセッション):

scala> trait MetaEntity extends Product
defined trait MetaEntity

scala> case class Test(i: Int, j: Int) extends MetaEntity
defined class Test

scala> def test[T <: MetaEntity](t: T) = {
     |   for (elem <- t.productIterator)
     |     println(elem.getClass.getName + " " + elem)
     | }
test: [T <: MetaEntity](t: T)Unit

scala> test(Test(1,2))

java.lang.Integer 1
java.lang.Integer 2

「内」製品の属性を読み取るには、型チェックを実行できます(例:iter.next.isInstanceOf [Product])。

于 2012-06-04T12:10:47.313 に答える
1

エンティティをマップとして表現してみませんか? 次に、キーを属性として簡単に反復処理し、Scala マップが実行できる他のすべての凝った処理を実行できます。

表現を非表示にしたい場合は、構成を使用する必要があります。つまり、マップをプライベート フィールドとして保存します。

このようなものから始めることができます:

class Entity {
  private[this] val map = collection.mutable.Map[String, Any]()
  def name = map("name").asInstanceOf[String]
  def attributes = map.keys
  ...
}
于 2012-06-04T12:39:53.377 に答える