2

ユーザーが「stop」を入力して readLn を非同期にしたときに、exit を使用して無限の読み取り印刷サイクルを作成したいと考えています。

import cats.effect.{ExitCode, IO, IOApp, Timer}

import scala.concurrent.duration._
import scala.io.StdIn
import scala.language.postfixOps
import cats.implicits._

object ReadWrite extends IOApp {
  val readLn: IO[String] = IO(StdIn.readLine())
  val readWriteName: IO[Nothing] = for {
    _     <- IO(println("write your name: "))
    name  <- readLn
    _     <- IO(println(s"Hello, $name"))
    t     <- name match {
      case "stop" => ???
      case _      =>  readWriteName
    }
  } yield t

  def run(args: List[String]): IO[ExitCode] =
    for {
      _ <- (Timer[IO].sleep(1 millisecond) *> readWriteName).start
      _ <- Timer[IO].sleep(100 second)
    } yield ExitCode.Success
}

使用しようとしましIO(println(s"Buy Buy"))たが、エラーメッセージが表示されます:

Error:(20, 11) type mismatch;
 found   : t.type (with underlying type Unit)
 required: Nothing
  } yield t

エラーなしで終了する方法は?

readLnまた、たとえば別のスレッドで IO を実行したい。

4

1 に答える 1