代码之家  ›  专栏  ›  技术社区  ›  Luke De Feo

使现有类在scala中实现特征

  •  3
  • Luke De Feo  · 技术社区  · 8 年前

    我有一个接受键值对的类,它可以以map对象或case类的形式出现。让我们定义以下抽象:

     trait Reportable {
        def getAttributes : Map[String,Any]
      }
    

    可报告的可能实现包括:

    • 实现的地图就是它本身
    • 一个case类我可以使用一些使用反射的东西从case类中获取属性并将其放入一个映射中

    问题是我不知道如何使Product(所有case类的基类)和Map类实现我的特性。我希望能够接受一个现有的类,并将其混合到可报告特性中,根据该类已有的方法实现它。

    1 回复  |  直到 8 年前
        1
  •  8
  •   Sascha Kolberg    8 年前

    我认为,你不能把一种特质混为一谈。

    然而,imho听起来像是 EnrichMyLibrary公司 图案示例 Map :

    trait Reportable {
      def getAttributes : Map[String,Any]
    }
    
    object Reportable {
      implicit class MapReportableOps(private val underlying: Map[String, Any]) extends Reportable {
        def getAttributes: Map[String, Any] = underlying
      }
    }
    

    用法:

    val reportables: List[Reportable] = Map("foo" -> "bar") :: Nil
    

    MapReportableOps 对于地图 Reportable 并创建一个 可报告 .

    推荐文章