Jill Clover
Jill Clover

Reputation: 2328

why use a method with no parameter lists over a val

I came across this function in Scala def nullable: Boolean = true. I understand what does this function do, but I want to know is there specific name for this kind of function, and what's the motivation not using var

Upvotes: 1

Views: 130

Answers (2)

oxbow_lakes
oxbow_lakes

Reputation: 134310

Firstly, I would be very precise in scala: use the word Function to only ever mean an instance of FunctionN and use the word Method when talking about a def (which may have zero or more parameter lists). Secondly, this most definitely does have a body (albeit not enclosed in braces). Its body is the expression true (i.e. a boolean literal).

I assume that you really mean to ask: "why use a method with no parameter lists over a val?"

When deciding whether to represent some property of your class, you can choose between a method and a value (advice: avoid using var). Often, if the property involves no side effects, we can use a def with no parameter lists (the scala idiom is that a def with a single, empty parameter list implies side-effects).

Hence we may choose any of the following, all of which are semantically equivalent at the use-site (except for performance characteristics):

case class Foo(s: String) {
  //Eager - we calculate and store the value regardless of whether
  //        it is ever used 
  val isEmpty = s.isEmpty
}

case class Foo(s: String) {
  //Lazy - we calculate and store the value when it
  //       it is first used 
  lazy val isEmpty = s.isEmpty
}

case class Foo(s: String) {
  //Non-strict - we calculate the value each time
  //             it is used 
  def isEmpty = s.isEmpty
}

Hence we might take the following advice

  • If the value is computationally expensive to calculate and we are sure we will use it multiple times, use val
  • If the value is computationally expensive and we may use it zero or many times, use lazy val
  • If the value is space-expensive and we think it will be generally used a most once, use def

However, there is an additional consideration; using a val (or lazy val) is likely to be of benefit to debugging using an IDE which generally can show you in an inspection window the value of any in-scope vals

Upvotes: 7

developer_hatch
developer_hatch

Reputation: 16224

The primary difference of the use of def or var/val is the when the value will be executed.

  • the def defines a name for a value, the value on the right will be executed when it is called (called by name), meaning it is lazy
  • and var defines a name for a value, and it is execute it's evaluated, eagerly upon definition

Upvotes: 0

Related Questions