【发布时间】:2023-03-21 05:30:02
【问题描述】:
我正在尝试编写一个可以处理不同数量键的通用存储库模块
trait Repo[K, V] {
def read(key: K): V
}
trait DynamoDBRepo extends Repo[K,V]{
def aRepo[K:StringIdentifiable,V]() = new Repo[K,V]{
val dynamoDBClient = ???
override def read(key: K, tableName: String): V = {
val tableKey: String = implicitly[StringIdentifiable].identify(key)
dynamoDBClient.Table(tableName).get(tableKey) //(*)
}
}
}
@typeclass trait StringIdentifiable[M] {
def identify(id: M): String
}
(*) 但是,dynamoDBClient.Table(tableName).get(key) 也可以将take a tuple 作为键(分区键和排序键)。
因此,我想以某种方式从 key:K override def read(key: K) 中提取 K 中的字符串或 (K,K) 中的 (String, String)
我首先尝试this 从实现 StringIdentifiable 类型类的元组中提取类型。我被卡住了。
Then tried to rewrite 一个 StringIdentifiable 类型类,当参数是一个键时返回 String,但当读取的参数是一个元组时返回 (String, String)。但我无法to use this method either。
我怎样才能在不失去抽象的情况下解决他的问题
【问题讨论】:
-
好吧,在这种情况下,我只需创建一个使用 ADT 的包装器:
sealed trait RepoKey; case class SimpleKey(key: String) extends RepoKey; case class PartitionedKey(partition: String, key: String) extends RepoKey。如果只有 2 个案例,任何进一步的概括都只是过度设计。
标签: scala typeclass shapeless path-dependent-type