scala隐式类:继承参数的所有成员

时间:2015-09-09 03:04:02

标签: scala implicit traits

我有一个非常有用的隐式类,我想扩展GenIterable

  import scala.collection.GenIterable
  implicit class WhatUpTho[S<:GenIterable[T],T](s:S) extends GenIterable[T]{
    def whatUpTho = println("sup yo")
  }

不幸的是,编译器不会让我写这个,因为它缺少trait GenIterable所需的79个方法或属性。我想将针对WhatUpTho所有请求推迟到其s参数未明确定义。

如何实现这一目标?

1 个答案:

答案 0 :(得分:6)

无需扩展GenIterable [T]。

object Conversions {
  implicit class WhatUpTho[S <: GenIterable[_]](s:S) {
    def whatUpTho = println("sup yo")
  }
}

import Conversions._

val s = List(1, 2, 3)
s.whatUpTho

关于泛型:

// Depending on the signature of your functions, you may
// have to split them into multiple classes.
object Conversions {

  implicit class TypeOfCollectionMatters[S <: GenIterable[_]](s:S) {
    def func1(): S = ...
    def func2(t: S) = ...
  }

  implicit class TypeOfElementsMatters[T](s: GenIterable[T]) {
    def func3(): T = ...
    def func4(t: T) = ...
  }

   // If you need both, implicit conversions will not work.
  class BothMatters[S <: GenIterable[T], T](s: S) {
    def func5: (T, S) = ...
  }
}

import Conversions._

val s = List(1, 2, 3)
s.func1
s.func2(List(4,5,6))
s.func3
s.func4(7)

// You have to do it youself.
new BothMatters[List[Int], Int](s).func5