尝试:
def big[T1, T2](func: T1 => T2) = func
def small(t1: Double, t2: Double) = (t1, t2)
big(small)
错误:
Type mismatch: Expected (NotInfered1) => NotInferedT2, actual: (Double, Double) => (Double, Double)
同样:
def big[T1, T2](func: (T1*) => T2) = func
我相信"大"的参数签名应该是接受带有未知数量参数的函数的其他东西。
答案 0 :(得分:3)
以下是几个选项:
1)使用tupled
- 将该函数转换为Function1
,以便编译器满意(不是用户虽然:)):
scala> def big[T1, T2](func: T1 => T2) = func
big: [T1, T2](func: T1 => T2)T1 => T2
scala> def small(t1: Double, t2: Double) = (t1, t2)
small: (t1: Double, t2: Double)(Double, Double)
scala> big(small)
<console>:10: error: type mismatch;
found : (Double, Double) => (Double, Double)
required: ? => ?
big(small)
^
scala> big(small _ tupled)
warning: there were 1 feature warning(s); re-run with -feature for details
res1: ((Double, Double)) => (Double, Double) = <function1>
2)更改big
的类型以获取产生T
的任何内容:
scala> def big[T](func: => T) = func
big: [T](func: => T)T
scala> big(small _)
res3: (Double, Double) => (Double, Double) = <function2>
scala> def verysmall(t1: Int) = t1
verysmall: (t1: Int)Int
scala> big(verysmall _)
res4: Int => Int = <function1>
请注意,在第一种情况下,它是Function1
采用元组,而在第二种情况下,它是Function2
需要2个参数。
看起来你正在寻找( => T)
语法。
答案 1 :(得分:1)
Scala没有采用任意数量参数的函数。方法可以是可变的,例如, def x(x: Int*)
,但函数必须从一个Function特征继承,例如Function1
,Function2
,强制他们拥有一定数量的参数。
但是,您可以使用带有元组的函数:
val small = (tuple: (Double, Double)) => tuple