需要两个隐式参数之一的Scala方法 [英] Scala method that needs either one of two implicit parameters
问题描述
我对是否可以创建具有类似想法的方法很感兴趣:
I'm interested if I can create method with similar idea:
def myMethod[T](param: T)(implicit oneOf: Either[TypeClass1[T], TypeClass2[T]]) = oneOf match ...
我尝试使用默认参数(我在akka中看到了类似的东西):
I've tried to use default parameters (I've seen somethin similar in akka):
def myMethod[T](param: T)(implicit t1: TypeClass1[T] = null, t2: TypeClass2[T] = null) =
if (t1 == null) ...
但是,这样一来,我无法强制Scala编译器找到其中至少一个.
However, that way I cannot force scala compiler to find at least one of them.
此外,我已经实现了从TypeClass1[T]
到Left[TypeClass1[T], TypeClass2[T]]
以及从TC2
到Right
的隐式转换,但是Scala编译器忽略了这种转换.
Also, I've implemented implicit conversion from TypeClass1[T]
to Left[TypeClass1[T], TypeClass2[T]]
and from TC2
to Right
, however Scala compiler ignores this conversions.
有什么办法做这样的事情吗?
Is there any way to do something like this?
推荐答案
显而易见的解决方案是创建可以使用TypeClass1
或TypeClass2
构造的新类型类.新的类型类实现了myMethod
所共有的功能,并将其映射到TypeClass1
或TypeClass2
上的适当方法.
The obvious solution is to create a new typeclass that can be constructed using either TypeClass1
or TypeClass2
. The new typeclass implements the functionality used by myMethod
that is common to both and maps it to the appropriate methods on TypeClass1
or TypeClass2
.
这里是一个例子:
trait TypeClass1[T] {
def showOne = println("Typeclass 1")
}
trait TypeClass2[T] {
def showTwo = println("Typeclass 2")
}
trait UnionTypeClass[T] {
def show
}
object UnionTypeClass {
implicit def t1[T](implicit ev: TypeClass1[T]) = new UnionTypeClass[T] {
def show = ev.showOne
}
implicit def t2[T](implicit ev: TypeClass2[T]) = new UnionTypeClass[T] {
def show = ev.showTwo
}
}
implicit object IntClass extends TypeClass1[Int]
implicit object StringClass extends TypeClass2[String]
def myMethod[T](param: T)(implicit ev: UnionTypeClass[T]) = {
ev.show
}
myMethod(0)
myMethod("hello")
这将打印
Typeclass 1
Typeclass 2
这篇关于需要两个隐式参数之一的Scala方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!