我正在使用Seq[T]
类型的集合,我为它编写了一个转换函数
foo(a: Seq[T): Seq[T] = ...
我想像这样打电话给foo
val a: Seq[T] = ...
a.foo
而不是
foo(a)
这可能吗?
我后来希望foo是通用的,即foo[T](a: Seq[T]): Seq[T] = ...
答案 0 :(得分:3)
是的,请查看Scala中的implicit classes 像这样:
object Helpers {
implicit class SeqWrap[T](seq: Seq[T]) {
def foo: Unit = {
println("BLA")
}
}
}
import Helpers._
Seq(1,2).foo // prints "BLA"
答案 1 :(得分:1)
您可以使用隐式类“pimp”Seq[T]
,如:
implicit class SeqEx[T](val seq: Seq[T]) extends AnyVal {
def foo: Seq[T] = ...
}
请参阅:https://alvinalexander.com/scala/scala-2.10-implicit-class-example
答案 2 :(得分:1)
是的,如果您通过隐式转换或隐式类实现扩展方法,那么它是可能的:
object Main {
def foo[T](a: Seq[T]): Seq[T] = ???
implicit class SeqWithFoo[T](a: Seq[T]) {
def foo = Main.foo(a)
}
def main(args: Array[String]): Unit = {
trait T
val a: Seq[T] = ???
a.foo
}
}
答案 3 :(得分:1)
您可以创建隐式方法,将Seq
翻译为RichSeq
,这将有您想要的额外方法。
class RichSeqSpecs extends FunSuite with Matchers {
test("richSeq") {
class RichSeq[T] (val seq: Seq[T]) {
def foo = "do something"
}
implicit def seqToRichSeq[T](seq: Seq[T]) = new RichSeq[T](seq)
Seq(1, 2, 3).foo shouldBe "do something"
Seq("hi", "how are you").foo shouldBe "do something"
}
}
OrElse,你甚至不必创建一个单独的隐式方法,你可以告诉RichSeq
类是隐含的,
class TypeSpecs extends FunSuite with Matchers {
test("richSeq") {
implicit class RichSeq[T] (val seq: Seq[T]) {
def foo = "do something"
}
Seq(1, 2, 3).foo shouldBe "do something"
Seq("hi", "how are you").foo shouldBe "do something"
}
}