Martin Kolinek
Martin Kolinek

Reputation: 2010

Type alias for inferred type

I have a method with a complicated return type and I would like to have a function which takes the result of this method as a parameter. Is it possible to create an alias for the return type of the method? Something like typeof from C++

e.g.

object Obj {
    def method(x:Int) = 1 to x
    type ReturnType = ???

    //possible solution if i know a parameter for which the method won't fail
    val x = method(1)
    type ReturnType = x.type

    //another possible solution, I don't need a parameter that won't fail 
    //the method but i still think there is a better way
    lazy val x = method(1)
    type ReturnType = x.type

    //I would then like to have a function which takes ReturnType as a parameter
    def doit(t:ReturnType) = Unit
}

The thing is that the compiler knows the type but I don't know how to get it from him.

Upvotes: 2

Views: 323

Answers (2)

EECOLOR
EECOLOR

Reputation: 11244

The only way I could think of is this:

class Return[T](f:() => T) {
  type Type = T
}

def getDifficultReturnType() = 1 to 10

val Return = new Return(getDifficultReturnType)

def doIt(t:Return.Type) = {

}

I am not sure if this is what you are looking for.

Upvotes: 2

0__
0__

Reputation: 67280

To my knowledge, this is not possible. Perhaps in a future Scala version with type macros.

In any case, leaving the type away if it's non-trivial is not a good design in my opinion. I understand that you don't want to type 80 characters, but if it's crucial to preserve that type (as it sounds), it should be explicated at some point.

You can use a type alias:

object Obj {
  type ReturnType = My with Very[LongAndComplicated] with Name
  // explicit type ensures you really get what you want:
  def method(x: Int): ReturnType = 1 to x  

  def doit(t: ReturnType) {}
}

Upvotes: 0

Related Questions