2013-06-03 73 views
1

我想創建一個功能g,需要一個功能f作爲參數,其中f有一個類型參數。我無法獲得編譯的g的簽名。一種嘗試是這樣的:傳遞函數參數類型作爲參數

scala> def mock1[A](): A = null.asInstanceOf[A] // STUB 
mock1: [A]()A 

scala> def mock2[A](): A = null.asInstanceOf[A] // STUB 
mock2: [A]()A 

scala> def g0(f: [A]() => A): Int = f[Int]() 
<console>:1: error: identifier expected but '[' found. 
     def g0(f: [A]() => A): Int = f[Int]() 
       ^

我可以得到它,如果我換行,需要一個類型參數的特質,像這樣的功能工作:

scala> trait FWrapper { def f[A](): A } 
defined trait FWrapper 

scala> class mock1wrapper extends FWrapper { def f[A]() = mock1[A]() } 
defined class mock1wrapper 

scala> class mock2wrapper extends FWrapper { def f[A]() = mock2[A]() } 
defined class mock2wrapper 

scala> def g(wrapper: FWrapper): Int = wrapper.f[Int]() 
g: (wrapper: FWrapper)Int 

scala> g(new mock1wrapper) 
res8: Int = 0 

有沒有一種方法可以讓我完成這沒有介紹包裝類?

回答

5

Scala並(目前)沒有對多態函數值的支持。你有兩個選擇:

  1. 堅持自己的包裝特徵(可能比較容易理解),從Shapeless
  2. 使用多態函數值(花哨,但也許有點複雜)
0

如何:

def mock[A](): A = null.asInstanceOf[A] 

    def g[A](f:() => A): A = f() 

    g(mock[Int]) 
+0

謝謝,但沒有按」工作。我的例子被過分簡化了。我需要能夠在'g'的主體內使用不同類型的參數來調用'f'。例如,像'DEF克(F:[A]()=> A):布爾= {F [字符串]()== F [INT]()的toString。}'。 –