codingsplash
codingsplash

Reputation: 5055

apply() returning the same object

I am trying to understand how Future works and I came across its apply(). The api says this about the apply()

Starts an asynchronous computation and returns a Future object with the result of that computation

I wanted to understand it better by creating a simple object, whose apply will return the same object with modified fields. For example, consider the below code:

object Rough extends App {
  trait Sample

  object Sample {
    var x: Int = 0
    def apply[T](body: => T): String= {
      "Hello " + body
    }
  }

  val s: String = Sample.apply("World")

  print(s)
}

Right now the apply is returning a String. I want it to return Sample[Int]. More specifically, I want the apply() to return Sample[Int] where the Int value will be the length of String characters which was passed to the apply(). How can I do this?

Upvotes: 1

Views: 127

Answers (1)

jwvh
jwvh

Reputation: 51271

You appear to be confused about a few unrelated Scala topics.

First off, apply() is just a method like any other. It's only special in that the name can be omitted when it is invoked. So Sample() is just a convenient shorthand for Sample.apply().

Now if you want a method that returns the singleton object that it is attached to, just have it return this.

object Sample {   // create a singleton object
  var x: Int = 0
  def apply(s: String): Sample.type = {
    x = s.length  // save some data
    this          // return a reference to this object
  }
}

val samp = Sample("Hi there")  // invoke the 'apply()' method
samp.x            // get the saved data --> res0: Int = 8

Upvotes: 1

Related Questions