Search code examples
scalafunctiontraitsfunctional-interface

Functional Interfaces in Scala


I have been working with Java for a while and now I am trying to learn Scala. I have a hard time understanding how to create a Functional Interface in Scala. I'm trying following code, but it's not working:

object Ex3 extends App {

trait Printer {
  def print(s: String): Unit
}

val p: Printer = x => println(x)

p("Hello") //does not want compile, error: 'Ex3.p.type' does not take parameters
}

p.s. I saw this example in an online course, and it worked.

UPD: I made a mistake in my code. It will work like this:

p.print("Hello)

also it works with apply method, as Mateusz Kubuszok said. Thanks everyone!


Solution

  • Ihor! Nice to meet you there:)

    p("Hello") - it means p.apply("hello"). But you didn't write apply method.

    So you can call it like that:

    p.print("Hello")