Wal*_*Cat 0 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")
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,编译器不会让我写这个,因为它缺少79所需的方法或属性trait GenIterable.我想将所有WhatUpTho未明确定义的请求推迟到其s参数.
我该如何做到这一点?
没有必要扩展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
Run Code Online (Sandbox Code Playgroud)
关于泛型:
// 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
Run Code Online (Sandbox Code Playgroud)