[英]Declare variable whose type is a function's return type
I'm currently using a type alias: 我目前正在使用类型别名:
type FooType = Int
val foo = (_: Int) * 2
def takeFooRet(x: FooType) = ...
however, I'd like to do something like: 但是,我想做类似的事情:
val foo = (_: Int) * 2
def takeFooRate(x: foo.RetType) = ...
I'm not seeing anything in Function1 . 我在Function1中什么都看不到。 Is it impossible? 不可能吗
It's not impossible, but you would need Function1
to expose its return type as a type member. 这不是不可能,但您需要Function1
将其返回类型公开为类型成员。 Unfortunately this is not the case, but you can wrap Function1
into something that gives you the information you need. 不幸的是,情况并非如此,但是您可以将Function1
包装到可以为您提供所需信息的内容中。 Here's a trivial example 这是一个简单的例子
class Function1Aux[T1, R](f: Function1[T1, R]) {
type Out = R
}
val foo = new Function1Aux((_: Int) * 2)
def takeFooRate(x: foo.Out) = x
I realize it's not pretty, but it shows that it's technically possible. 我意识到它并不漂亮,但是它表明在技术上是可行的。
You need to know input type or parametrize your 'takeFooRate' with some type 您需要知道输入类型或使用某些类型参数化您的“ takeFooRate”
def takeFooRate[+Out](x: Int => Out) = ...
or 要么
def takeFooRate[-In,+Out](x: In => Out) = ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.