我有一个特点,可以做到以下几点:
trait MyTrait[T] {
def doSomething(elems: Seq[T])
}
然后我有一个工厂,可以创建这个特性的实现实例:
object MyTrait {
def apply(): MyTrait = {
new StringTrait()
}
}
现在具体实现如下:
class StringTrait extends MyTrait[String] {
def doSomething(elems: Seq[String]) = {
// some generic logic here
// some specific logic here (this code bit depends on the type of implementation)
// some generic logic here
}
}
我现在如何制作StringTrait,以便从中传递特定的行为并在抽象类中定义泛型逻辑?一种方法是将行为作为thunk传递,但是这意味着我必须修改我的doSomething(...)方法以获取我希望避免的附加参数。
答案 0 :(得分:0)
您有几个选项,为了便于说明,我假设特定类型的行为是Seq [T] => T(即你取一个T序列并产生一个T):
基于继承:
trait MyTrait[T] {
def doTypeSpecificStuff(a: Seq[T]): T
def doSomething(elems: Seq[T]): T = {
// generic code stuff
val t: T = doTypeSpecificStuff(elems)
// more generic code
t
}
}
class StringTrait extends MyTrait[String] {
def doTypeSpecificStuff(elems: Seq[String]) = {
elems.reduceOption(_ + _).getOrElse("")
}
}
def client(thing: MyTrait[String], elems: Seq[String]) {
thing.doSomething(elems)
}
键入类:
trait MyTypeClass[T] {
def doTypeSpecificStuff(a: Seq[T]): T
}
object StringTypeClass {
implicit val instance: StringTypeClass = new StringTypeClass()
}
class StringTypeClass extends MyTypeClass[String] {
def doTypeSpecificStuff(elems: Seq[String]): String = {
elems.reduceOption(_ + _).getOrElse("")
}
}
object TypeClassDependentBehaviour {
def doSomething[T](elems: Seq[T])(implicit tp: MyTypeClass[T]): T ={
//some code
val stuff: T = tp.doTypeSpecificStuff(elems)
//more generic code
stuff
}
}
def client(elems: Seq[String]) {
TypeClassDependentBehaviour.doSomething(elems)
}