目前我使用一个类型别名:声明变量,其类型是一个函数的返回类型
type FooType = Int
val foo = (_: Int) * 2
def takeFooRet(x: FooType) = ...
不过,我想这样做:
val foo = (_: Int) * 2
def takeFooRate(x: foo.RetType) = ...
我不是看到任何东西Function1。这是不可能的吗?
目前我使用一个类型别名:声明变量,其类型是一个函数的返回类型
type FooType = Int
val foo = (_: Int) * 2
def takeFooRet(x: FooType) = ...
不过,我想这样做:
val foo = (_: Int) * 2
def takeFooRate(x: foo.RetType) = ...
我不是看到任何东西Function1。这是不可能的吗?
你需要知道输入类型或某些类型的
def takeFooRate[+Out](x: Int => Out) = ...
或
def takeFooRate[-In,+Out](x: In => Out) = ...
以及它需要知道的类型:) – 2014-10-03 10:18:08
这不是不可能的参数化你的“takeFooRate”,但你需要Function1
揭露它的返回类型为类型成员。不幸的是,情况并非如此,但您可以将Function1
包装成可以提供所需信息的东西。这是一个简单的例子
class Function1Aux[T1, R](f: Function1[T1, R]) {
type Out = R
}
val foo = new Function1Aux((_: Int) * 2)
def takeFooRate(x: foo.Out) = x
我意识到这并不漂亮,但它表明它在技术上是可行的。
那么,你可以添加隐式def Fn1ToAux [A,B](f:Function1 [A,B]):Function1Aux [A,B] = new Function1Aux [A, B](f)'并且使用你的普通函数 – laughedelic 2014-10-03 16:06:39
@如果这样可以工作,你可以用'implicit class'替换'class'并且用它来完成,但显然访问一个类型成员不足以触发隐式转换。 – 2014-10-03 16:22:07
'Function1'没有抽象类型,所以我认为你需要一些隐式转换,而实现将是宏。 – 2014-10-03 01:47:46