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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With