MetallicPriest
MetallicPriest

Reputation: 30795

How to declare a function with val in Scala that takes no Input

We know that in scala, you can declare a function like a variable, using val. For example, if I want to declare a function that returns the square of a number, I can write it like this.

val square: Long => Long = x => x * x

But how do I declare a function with this style, if it takes no input. For example, I wanted to declare a function which gives time in secs, so I declared it like this.

val secs: Unit => Long = x => System.currentTimeMillis / 1000

Is there a more elegant way to declare such functions, as the x => here is kind of useless. Note that I don't want to declare it using def.

Upvotes: 1

Views: 301

Answers (2)

joesan
joesan

Reputation: 15425

You can use functional interfaces like this:

object Seconds extends (Unit => Long) {
  def apply(): Long = System.currentTimeMillis / 1000
}

You can then call it like:

Seconds()

Upvotes: 1

Jeffrey Chung
Jeffrey Chung

Reputation: 19527

One approach is to define secs as follows:

val secs = () => System.currentTimeMillis / 1000

Call it with secs().

Upvotes: 4

Related Questions