mkUltra
mkUltra

Reputation: 3068

Constant function from Any to Unit in Scala standard library

I am looking for a constant function in Scala standard library with signature Any => Unit.

I noticed that often is used as anonymous function _ => () so come with a question:

There is any particular reason to don't have a constant function in the standard Scala library?

P.S.: I still admit that maybe this function exists and I just didn't search for it enough.

Upvotes: 2

Views: 92

Answers (2)

Mario Galic
Mario Galic

Reputation: 48430

Consider defining singleton object function which can act as constant like so

object constFun extends (Any => Unit) { def apply(x: Any): Unit = () }

We can use it in usual ways

List(1,2,3).foreach(constFun)

Upvotes: 3

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

const can be accessed using Function.const

scala> val f = Function.const(())(_: Any)
f: Any => Unit = $$Lambda$1264/445350376@234cff57

Upvotes: 4

Related Questions