How can I provide a compile-time guarantee so that my method returns the same object that it receives in Scala?

In the Scala class, I can conveniently declare the return type of the method this.typeto ensure that it will return the same object it was called on:

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

Is there a way that I can precisely indicate that the method that takes this parameter AnyRefwill return this link for sure? The following snippet does not provide this guarantee, I could return any instance A:

def processAndReturn[A <: AnyRef](obj: A): A = {
  // work with obj
  obj
}
+5
source share
4 answers

The huitseeker offer is valid with the option -Ydependent-method-types:

$ 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

, , - , , , . Scala (. Adriaan Moor ). , , ( ) Scala.

+8

, obj.type , , , . , .47:

(...) ; .

- , , .

+3

huitseeker Kipton, , , .

, , , - , . ?

:

class Counter {
  var i = 0
  override def toString = i.toString
}

def incr(c: Counter): Counter = { c.i += 1; c }

val two = incr(incr((new Counter)))
// two: Counter = 2

incr , . , , :

def incorrect_incr(c: Counter): Counter = { 
  c.i += 1
  new Counter // should return c but does not
}

val notTwo = incorrect_incr(incorrect_incr(new Counter))
// notTwo: Counter = 0

, , , ( , ):

case class Id[T <: AnyRef](t:T) {
  def map[U](f: (T) => U): Id[T] = { 
    f(t)
    this
  }
  def get: T = t
}

val reallyTwo = Id(new Counter).map(incorrect_incr).map(incorrect_incr).get
// reallyTwo: Counter = 2

mapbasically guarantees that the function is called for its side effect, getexpands the value ...

+1
source

Question: if you are going to return what you went through, why not just use void? After all, you already have an object in the calling code, right?

0
source

All Articles