如何基于Type Class实现支持.increment()的Scala通用隐式类?
问题描述
我已经实现了针对Int类型的隐式类,代码如下:
implicit class IntIncrement(val underlying: Int) extends AnyVal { def increment(): Int = underlying + 1 }
这段代码可以正常运行,支持1.increment()这样的调用方式。
为了让更多类型都能拥有.increment()方法,我尝试用Type Class的方式重构:
trait Increment[T] { def increment(value: T): T } object Increment { implicit val implInt: Increment[Int] = new Increment[Int] { def increment(value: Int): Int = { value + 1 } } } def increment[T](value: T)(implicit valueIntDec: Increment[T]): T = { valueIntDec.increment(value) }
但现在只能通过increment(1)的形式调用,没法用1.increment()这种更直观的语法。我想知道能不能为所有拥有Increment[T]隐式实例的类型T创建对应的隐式类,类似下面(语法错误的)代码的效果:
implicit class ImplicitIncrement[T](val underlying: implicit Increment[T]) extends AnyVal { def increment(): T = increment(underlying) }
解决方案
当然可以实现,你只需要把Increment[T]隐式参数放到隐式类的单独参数列表中,或者使用Scala的上下文绑定语法来简化代码。
方法一:单独隐式参数列表
保留你已有的Increment trait和伴生对象,添加以下隐式类:
implicit class IncrementOps[T](val underlying: T) extends AnyVal { def increment()(implicit inc: Increment[T]): T = inc.increment(underlying) }
这样,只要某个类型T存在对应的Increment[T]隐式实例,就可以直接调用T实例的.increment()方法,比如1.increment()就能正常执行。
方法二:上下文绑定语法
用上下文绑定T: Increment来简化代码,它本质上是上面写法的语法糖:
implicit class IncrementOps[T: Increment](val underlying: T) extends AnyVal { def increment(): T = implicitly[Increment[T]].increment(underlying) }
这里T: Increment要求作用域内存在Increment[T]的隐式实例,然后通过implicitly[Increment[T]]获取这个实例来调用方法。
说明
你之前的写法语法错误,因为隐式参数不能直接放在主构造参数的val声明里,必须放在单独的参数列表中,或者使用上下文绑定来声明类型约束。
内容的提问来源于stack exchange,提问作者doliphin
相关产品推荐
相关产品推荐

