Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I provide a compile-time guarantee that my method will return the same object it gets in Scala?

In a Scala class, I can conveniently declare the return type of a method to be this.type to guarantee that it will return the same object it is called on:

class Foo {
  def bar: this.type = this
}

Is there a way I can similarly specify that a method that accepts a given AnyRef param will return that reference exactly? The following snippet does not provide this guarantee, I could return any instance of A:

def processAndReturn[A <: AnyRef](obj: A): A = {
  // work with obj
  obj
}
like image 811
Jean-Philippe Pellet Avatar asked Jul 30 '11 22:07

Jean-Philippe Pellet


1 Answers

huitseeker's suggestion is actually valid with the -Ydependent-method-types option:

$ scala -Ydependent-method-types
Welcome to Scala version 2.9.0.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_24).

scala>   def processAndReturn[A <: AnyRef](obj: A): obj.type = {
     |       // work with obj
     |       obj
     |   }
processAndReturn: [A <: AnyRef](obj: A)obj.type

scala> processAndReturn("hi")
res1: java.lang.String = hi

From this thread, I gather that experimental dependent method types have been around for a while, and there's even a published paper using them, but the implementation may be buggy. There has been some discussion about reworking Scala's type system foundations (see Adriaan Moor's slides on Dependent Object Types). If it works out, I imagine that dependent method types (among other things) will be completely kosher in future versions of Scala.

like image 71
Kipton Barros Avatar answered Oct 13 '22 00:10

Kipton Barros