2017-07-14 106 views
0

在斯卡拉使用Guice,我试图重现下面的Java代码。斯卡拉依赖注入泛型类

美孚接口和类声明:

public interface Foo[T] {} 
public class FooImpl[T] implements Foo[T] {} 

吉斯绑定代码:

bind(Foo.class).to(FooImpl.class); 

和一个使用的例子是;

@Inject 
public class Bar(Foo<String> foo) {} 

在Scala中,我的第一个赌注是:

bind(classOf[Foo]).to(classOf[FooImpl]) 

但它抱怨 'Foo类型需要一个类型参数' 如何在Scala中实现这一目标?

谢谢

+0

怎么样'绑定(classOf [富])。to(classOf [FooImpl ])' – frozen

+1

'bind(classOf [Foo [_]])。(classOf [FooImpl [_]])' – Dima

+0

嗨迪玛,谢谢你的回答。它看起来像是在工作,但是,我现在无法确认,因为我正面临另一个问题。我有两个隐式参数在我的类,看起来像他们没有正确提供使用Guice和注入。如果它确实有效,我会让你知道,这样你就可以用它回答我的问题。 – Jeep87c

回答

0

你的问题有错误,因此它可以让你一个错误的答案。

让我们先来解决你的概念想法。有trait

trait Foo[T] { def hello: T } 

工作得很好。但随后,延长这一特质的具体开班会,FE:

class FooImpl1 extends Foo[Int] { override def hello: Int = 42 } 
class FooImpl2 extends Foo[String]{ override def hello: String = "test" } 

他们可能是没有:

class FooImpl[Int] extends Foo[Int] { override def hello: Int = 42 } 
class FooImpl[String] extends Foo[String]{ override def hello: String = "test" } 

因为那样的话,在IntString只是NAME为一个通用参数。它可能也是AB,但你只是困惑自己。


已经整理出了这,你知道知道你有FooImpl1FooImpl2。 他们需要不同的名称,因为您不能在同一范围内命名两个相同的类!

而且它很好。因为当你:

bind(classOf[X]).to(classOf[Y]) 

你告诉每当你的类将调用InterfaceTraitX的方法,你想提供Y类的实现。

必须提供一个你可以实例化的类!你不能用泛型参数实例化一个类。

而且,为了完成,你适当的结合应该是这样的:

bind(new TypeLiteral[Foo[Int]](){}).to(classOf[FooImpl1]) 
bind(new TypeLiteral[Foo[String]](){}).to(classOf[FooImpl2])