Somasundaram Sekar
Somasundaram Sekar

Reputation: 5524

Anonymous function that matches signature () => Unit : Scala

Below lines of code are self explanatory

type a = () => Unit

def k(a_ : a) = {
  a_()
}

def g(): Unit = {
  println("Hello World")
}

k(g)

My question is how do I specify an anonymous function of type a while calling k?

Upvotes: 0

Views: 146

Answers (1)

dk14
dk14

Reputation: 22374

I hope these lines are also self-explanatory:

scala> k(() => println("Hello!")) //to your first question
Hello!

For the second question:

scala>  def k(i: Int)(a_ : a) = {
  a_(i)
}
k: (i: Int)(a_: Int => Unit)Unit

scala> k(5)(g)
Swami saranam 5

P.S. I wouldn't recommend to start type alias name with lower-case.

Upvotes: 2

Related Questions