我有一个类在这样的其他类中注入的类中定义的隐式类
class A {
implicit class B(s: String) {
def b = ???
}
}
class C(a: A) {}
有没有办法从类C访问隐式类B(特别是它的方法b),而无需显式导入它? (请注意,A类不能成为特征,因为它也会注入一些类。)
解决方案1(导入a._
)
嗯,是的,正如评论中已经指出的那样,从你的要求来看,为什么你不会在a._
的体内导入C
并不明显:
class A {
implicit class B(arg: String) {
def b: String = ???
}
}
class C(a: A) {
import a._
{
println("hello".b)
}
}
这一行确实没有伤害任何人。
如果你仍然不喜欢它,那么问题可能在其他地方。因此我的第二个建议。
解决方案2(从A
-syntax中分离类型类.b
接口)
另一个解决方案不是关于代码中import
s数量的减少,它甚至没有将B
保持在A
中。但它可能会解决另一个你可能无法明确表达的问题:它将A
提供的功能与B
提供的语法分开。
以下代码片段的结构受到Scala Cats库的设计的启发,该库遵循一个非常明确的隐式声明策略,总是将类型类定义与语法分开。
主要想法是:
AIntf
的实现提供了实际功能B
只提供了一些额外的“pimp-my-library”式方法我们希望将这两件事分开。
这是如何分离它们,从而也避免import a._
内部的C
。首先,定义描述A
提供的功能的界面:
trait AIntf {
def usefulOperationOnStrings(s: String): String
}
然后你可以用几个不同的A来实现它:
class A extends AIntf {
def usefulOperationOnStrings(s: String): String = "<foo>" + s + "</foo>"
}
class A2 extends AIntf {
def usefulOperationOnStrings(s: String): String = s.toUpperCase
}
请注意,对象B
已从A
消失。相反,它在一个单独的syntax
包中移动,并重命名为A_Ops
。 b
方法也被重命名为a
:
object syntax /* should be package, object only for script */ {
object a {
class A_Ops(wrapped: String, ai: AIntf) {
def a: String = ai.usefulOperationOnStrings(wrapped)
}
implicit def everyStringHasAOps(s: String)(implicit ai: AIntf): A_Ops = {
new A_Ops(s, ai)
}
}
}
这是你如何使用它:
A_Intf
syntax.a._
a
的C
参数声明为隐含的"string".a
中使用C
语法而无需进一步导入。在代码中:
import myproject.AIntf
import myproject.syntax.a._
class C(implicit val a: AIntf) {
{
println("hello".a)
}
}
现在AIntf
和语法.a
的实现变得独立。你可以注入A2
而不是A
。或者您可以将语法从"str".a
更改为"str".somethingEntirelyDifferent
。
完整的代码片段:
import scala.language.implicitConversions
object myproject /* should be package, object only for script */ {
trait AIntf {
def usefulOperationOnStrings(s: String): String
}
object syntax /* should be package, object only for script */ {
object a {
class A_Ops(wrapped: String, ai: AIntf) {
def a: String = ai.usefulOperationOnStrings(wrapped)
}
implicit def everyStringHasAOps(s: String)(implicit ai: AIntf): A_Ops = {
new A_Ops(s, ai)
}
}
}
class A extends AIntf {
def usefulOperationOnStrings(s: String): String = "<foo>" + s + "</foo>"
}
class A2 extends AIntf {
def usefulOperationOnStrings(s: String): String = s.toUpperCase
}
}
import myproject.AIntf
import myproject.syntax.a._
class C(implicit val a: AIntf) {
{
println("hello".a)
}
}
val c1 = new C()(new myproject.A)
val c2 = new C()(new myproject.A2)
// prints:
// <foo>hello</foo>
// HELLO
不幸的是,我不知道guice
将用隐含的论点做什么,还没有尝试过。它可能会迫使你写
class C @Inject()(val a: AIntf) {
implicit aintf: AIntf = a
...
}
然后变得比第一部分中提到的简单的import
更长。
正如评论中所述,只是import a._
:
class A {
implicit class B(s: String) {
def b: String = "hello "+ s
}
}
class C(a: A){
import a._
val hello = "world".b
}
val c = new C(new A)
c.hello // "hello world"