简体   繁体   中英

scala implicit class: inherit all members of parameter

I've got this terribly useful implicit class that I want to extend GenIterable :

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

Unfortunately, the compiler won't let me write this because it's missing 79 methods or attributes required by the trait GenIterable . I'd like to defer all requests against WhatUpTho not specifically defined to its s parameter.

How do I make that happen?

There's no need to extend 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

About the generics:

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM