Erik Kaplun
Erik Kaplun

Reputation: 38217

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. Is it impossible?

Upvotes: 0

Views: 86

Answers (2)

Gabriele Petronella
Gabriele Petronella

Reputation: 108101

It's not impossible, but you would need Function1 to expose its return type as a type member. Unfortunately this is not the case, but you can wrap Function1 into something that gives you the information you need. 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.

Upvotes: 3

Eugene Zhulenev
Eugene Zhulenev

Reputation: 9734

You need to know input type or parametrize your 'takeFooRate' with some type

def takeFooRate[+Out](x: Int => Out) = ...

or

def takeFooRate[-In,+Out](x: In => Out) = ...

Upvotes: 1

Related Questions