0

I wrote an implicit conversion from Scala functions to Java functions:

import java.util.function.{Function => JavaFunction}

implicit def toJavaFunction[T, V](f: (T) => V): JavaFunction[T, V] = {
  new JavaFunction[T, V] {
    override def apply(input: T) = f(input)
  }
}

However, IntelliJ suggests converting this to a single abstract method:

implicit def toJavaFunction[T, V](f: (T) => V): JavaFunction[T, V] = {
  (input: T) => f(input)
}

When I change to the second implementation, functions wrapped in this method run forever and execution never terminates. What's different about the second method that's causing it to behave this way? Is there something that IntelliJ is missing?

pbeardshear
  • 910
  • 7
  • 8
  • Which version of **Scala** are you using? Probably the problem is that on your second example basically it seems you are calling yourself recursively... Just that, that's not true, at least since `2.12` _(I believe this was introduced since `2.11`, but not sure tough)_ that conversion already exists _(I can just write this on the **REL** ` val jf: java.util.function.Function[String, Int] = s => s.toInt`)_, which probably is why Intellij suggest the change. I tested your second example on the **RELP** and it works too, so I am not sure what would be the problem on your case. – Luis Miguel Mejía Suárez Mar 28 '19 at 18:07
  • 1
    @LuisMiguelMejíaSuárez That the `s => s.toInt` is accepted as `java.util.function.Function` is not an implicit conversion, it's the SAM. I also couldn't reproduce the problem. – Andrey Tyukin Mar 28 '19 at 18:37
  • @AndreyTyukin Thanks for the clarification, I already knew that it was not an _implicit conversion_, but something more low level on the compiler. However, did not know what it was. So, thanks for the info both for me and for those reading this. – Luis Miguel Mejía Suárez Mar 28 '19 at 18:53
  • This is on version 2.11. I added the `-Xexperimental` flag to my compiler options and now the second option is working as well. I wonder if I have a config mismatch or something in IntelliJ that's telling it that SAM is available by default. – pbeardshear Mar 28 '19 at 18:57
  • Please check https://stackoverflow.com/questions/36828074/implicit-conversion-from-scala-function-to-java-function. Looks like duplicate question. – KZapagol Mar 29 '19 at 09:18
  • Possible duplicate of [Implicit conversion from Scala function to Java Function](https://stackoverflow.com/questions/36828074/implicit-conversion-from-scala-function-to-java-function) – pbeardshear Mar 29 '19 at 15:33
  • @KZapagol you're right. I did read that question before posting mine but I guess I didn't read it close enough. Voted to close as duplicate. – pbeardshear Mar 29 '19 at 15:33

0 Answers0