0

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?

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your insight. What if I really want to specify T? I have some other even more useful functions that won't play nice if they don't know all the datatypes are the same. Better solutions notwithstanding, is the original desideratum even possible?
For example: def yoDawgYo = s zip s yields the compile-time error: type mismatch; found : S required: scala.collection.GenIterable[B] among others of similar bent.
Depending on the signature of your functions, you may have to split them into multiple classes. I updated the answer with sample code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.