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。}'。 –