如何在Scala中利用mkNumericOps? [英] How to take advantage of mkNumericOps in Scala?

查看:38
本文介绍了如何在Scala中利用mkNumericOps?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试定义一种新的类型,其行为本质上可以像数字一样(具体来说,假设 Double ).我想在此类型上重载运算符,并且可以显式地执行此操作,但是为了避免重复,我想利用

I'm trying to define a new type that can behave essentially like a number (for concreteness, let's say a Double). I'd like to overload operators on this type and I could do this explicitly, but to avoid repetition, I would like to advantage of the methods in NumericOps, which are defined in terms of the abstract methods in Numeric. My understanding is I should be able to just override the methods in Numeric and get the others for free.

这是我能想到的最简单的尝试:

Here's the simplest attempt I can think of:

class Container(val value: Double) extends Numeric[Container] {
  override def plus(x: Container, y: Container): Container =
    new Container(x.value + y.value)

  // override minus, times, etc.

  override def toString: String = value.toString
}

println(new Container(1) + new Container(1))

但是,这给了我一个类型不匹配的错误.

However, this gives me a type mismatch error.

我对隐式的理解仍然很不稳定,但是我本以为 Container 继承的 implicit def mkNumericOps(lhs:Container):NumericOps 可以节省一天的时间隐式转换要添加到 NumericOps 对象的两个 Container 对象,然后使用根据 Container.plus定义的 + 方法添加它们.

My understanding of implicits is still quite shaky, but I would have thought the implicit def mkNumericOps(lhs: Container): NumericOps inherited by Container would save the day by implicitly converting the two Container objects being added to NumericOps objects and then adding them using the + method defined in terms of Container.plus.

我在这里出什么毛病了,我该如何解决?

What am I getting wrong here and how can I fix this?

推荐答案

以下是补充Luis的typeclass注释的示例

Here is an example to supplement Luis' typeclass comment

final case class Container(value: Double)

object Container {
  implicit val containerNumeric: Numeric[Container] = new Numeric[Container] {
    override def plus(x: Container, y: Container) = Container(x.value + y.value)
    override def minus...
  }
}

import Numeric.Implicits._
Container(1) + Container(1)

输出

res0: Container = Container(2.0)

导入提供 <代码> infixNumericOps 编译器用来自动重写为

The import provides infixNumericOps which compiler uses to automatically rewrite to

infixNumericOps(Container(1)) + Container(1)

这篇关于如何在Scala中利用mkNumericOps?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆