2016-08-16 23 views
1

調用方法,我有以下方法:和一個隱含的參數

def test[T](implicit ev: T <:< Int, t : T) = println(t) 

我怎麼能打電話嗎?我試圖

test(10) 

但是,編譯器打印出以下錯誤:

所有的
Error:(19, 9) not enough arguments for method test: (implicit ev: <:<[T,Int], implicit t: T)Unit. 
Unspecified value parameter t. 
    test(10) 
     ^

首先,我認爲我們可能只是省略隱含參數,並指定唯一明確的。其次,爲什麼說參數t是隱含的?

implicit t: T 

它是如何工作的?

回答

4

First of all, I thought that we could just omit implicit parameters and specify only explicit ones.

您既可以指定列表中的所有含義,也可以不指定它們。 According to the specification,如果一個參數被標記爲隱,整個參數列表標記爲好:

An implicit parameter list (implicit p1, ……, pn) of a method marks the parameters p1, …, pn as implicit.


secondly, why does it's saying that that the parameter t is implicit?

因爲什麼在你的第一部分回答了。

如果你仍然想調用它這樣,你可以使用implicitly

test(implicitly, 10) 

一般情況下,建議你需要在一個單獨的參數列表隱式:

def test[T](i: Int)(implicit ev: T <:< Int) = println(t) 
+0

+爲規格參考。 – user3663882

3

的問題是,隱含的參數應該是在自己的名單,像這樣:

def test[T](t : T)(implicit ev: T <:< Int) = println(t) 

給一個嘗試!

+0

嗯。 ..那麼我的問題中的聲明意味着什麼?編譯器如何解釋它? – user3663882

+0

這只是意味着ev和t參數都被認爲是隱含的。這就是爲什麼編譯器指出t是隱含的。 –

+0

因此,如果我們想要聲明多個隱式參數,我們可以多次忽略寫入隱式。正確? – user3663882