Search code examples
scalascala-catscats-effect

How to call Cats typeclass method without specifying it explicitly?


I want to write that code:

IO.foreverM:
  IO.sleep(1.seconds) *> IO.println("Tick")

But it doesn't compile. However this code compiles:

FlatMap[IO].foreverM:
  IO.sleep(1.seconds) *> IO.println("Tick")

Can the first one code be complied somehow?


Solution

  • The IO object doesn't contain aliases for every single typeclass operation it supports. There's no import that provides an IO.foreverM, though you could certainly write one, and there's been a proposal to add all such methods to the IO object for this reason.

    In general most code you see using cats will prefer using typeclass methods on instances instead of via companion objects. Like Luis suggested in the comments, (IO.sleep(1.seconds) *> IO.println("Tick")).foreverM