【问题标题】:How to write a method to take arbitrary classes in Scala如何在 Scala 中编写一个获取任意类的方法
【发布时间】:2018-06-24 14:09:36
【问题描述】:

编写可在任何类上运行的方法的正确方法是什么 定义了加法运算?

我以为是这样的

def trajectory[A <: {def +(a:A):A}](a:A): A = {
    a + a
}

但它不起作用。

【问题讨论】:

    标签: scala structural-typing


    【解决方案1】:

    我会选择type class

    trait Semigroup[A] {
      def mappend(a0: A, a: A): A
    }
    
    object Semigroup {
      implicit val intAdditionSemigroup: Semigroup[Int] = new Semigroup[Int] {
        override def mappend(a0: Int, a: Int): Int = a0 + a
      }
    }
    

    当你想使用它时,你将它添加为类型参数的隐式约束:

    def foo[A](a0: A, a: A)(implicit semigroup: Semigroup[A]): A = {
      semigroup.mappend(a0, a)
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      • 1970-01-01
      • 2019-11-20
      相关资源
      最近更新 更多