【问题标题】:How to use shapeless to abstract a repository client into a generic repository module如何使用 shapeless 将存储库客户端抽象为通用存储库模块
【发布时间】: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


【解决方案1】:

如果问题中的要求是您的解决方案必须满足的所有要求,则根本不需要无形、依赖于路径的类型和类型类。

sealed trait RepoKey[K] // TBH I am not sure if genericness here is even needed in your case...
case class SimpleKey(key: K) extends RepoKey[K]
case class PartitionedKey(partition: K, key: K) extends RepoKey[K]

trait Repo[K, V] {
  def read(key: RepoKey[K]): V
}

class DynamoDBRepo(dynamoDBClient: ...) extends Repo[String, V] {

  def read(key: RepoKey[String]): V = key match { 
    case SimpleKey(key)                 => ...
    case PartitionedKey(partition, key) => ...
  }
}

即使您将密钥存储为 String 以外的其他内容,您唯一需要的类型类也将类似于:

trait KeyExtractor[K] {
  def extract(key: RepoKey[K]): String
}

几乎可以肯定不需要推导,但需要一个明确的定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多