Implicit conversions causing infinite recursion, but it should not be typecheck

I am trying to write a Specs2 test for a class that takes a Squants Time value as a parameter. The trick is that both tools define an implicit, which adds a method called "seconds" to convert the number to its own representation (squants.time.Seconds in one case and org.specs2.time.Duration in the other) and unfortunately wrong seems to take precedence.

val a = new MyClass(10 seconds)  // doesn't build because MyClass wants a Time instead of a Duration

To be clear, I could get around this without relying on implicits to create Squants Time, which is not a question.

I like implicits more, so I decided to add an implicit duration conversion in Times:

implicit def specsTimeToSquantsTime(t: org.specs2.time.Duration): squants.time.Time = squants.time.Seconds(t.toSeconds)

This happened with typecheck, but when I ran the test, I got a stack overflow, and the stack trace didn’t make much sense, it said that my implicit conversion was calling itself (which would not be typecheck, and even if it is still not possible, given the code above!):

[error] package.TestConversions$.specsTimeToSquantsTime(TestConversions.scala:9)
[error] package.TestConversions$.specsTimeToSquantsTime(TestConversions.scala:9)
[error] package.TestConversions$.specsTimeToSquantsTime(TestConversions.scala:9)
...

So, I have three questions: what is going on here? Is there a better way to do this? Can I manually hide Int => Duration implicitly?

+4
source share
1 answer

The method is toSecondsdefined inside the class Time:

final class Time private (val value: Double) extends Quantity[Time] {    
  ...
  def toSeconds = to(Seconds)
  ...
}

https://github.com/garyKeorkunian/squants/blob/master/src/main/scala/squants/time/Time.scala

, , Duration, , specsTimeToSquantsTime, Duration.toSeconds, Duration Time, .. , , , , (. ), .

NoTimeConversions , :

( Akka,

+3

Source: https://habr.com/ru/post/1570899/


All Articles