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
有沒有一種方法可以讓我完成這沒有介紹包裝類?
謝謝,但沒有按」工作。我的例子被過分簡化了。我需要能夠在'g'的主體內使用不同類型的參數來調用'f'。例如,像'DEF克(F:[A]()=> A):布爾= {F [字符串]()== F [INT]()的toString。}'。 –