2017-07-14 109 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])