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!
CodePudding user response:
val p: Printer = x => println(x)
should indeed compile because Printer
is a Single Abstract Method - its only abstract method is of signature String => Unit
so if the compiler don't have to infer Printer
, it can take the function that matches the method signature and add the rest.
But p("Hello")
cannot work. To be able to call Printer
value, it would have to have a method named apply
defined, and there isn't one in your definition.
CodePudding user response:
We have this trait:
trait Printer {
def print(s: String): Unit
}
Now we can see, what happened if we try to implement it:
val p: Printer = new Printer {
override def print(s: String): Unit = println(s)
}
We can see that our print
method accepts one argument with the type String
, so let's start with the function that accepts it:
val p: Printer = (s: String) => ???
And now add the implementation, we would like just print it, so let's do it:
val p: Printer = (s: String) => println(s)