ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Function value signature for generics, context functions
    scala/scala3 2024. 3. 22. 01:01
    import scala.concurrent.duration.*
    import scala.concurrent.{Await, ExecutionContext, Future}
    
    def processOption[A](opt: Option[A]): String = opt match {
      case Some(v) => s"[$v]"
      case None    => "[]"
    }
    
    @main def main(): Unit = {
    
      /** Generics in functions
        */
      val processOptionFunction: [A] => Option[A] => String = {
        [A] => (opt: Option[A]) => processOption(opt)
      }
    
      processOptionFunction(Some(1))
    
      /** Context functions
        */
      def f(x: Int)(using ExecutionContext): Future[Int] = Future { x * 100 }
      val f_signature: Int => ExecutionContext ?=> Future[Int] = f
    
      val g: ExecutionContext ?=> Int => Future[Int] = (x: Int) => Future { x + 1 }
    
      given ExecutionContext = scala.concurrent.ExecutionContext.global
    
      val c = for {
        a <- f(2)
        b <- g(4)
      } yield a + b
    
      val r = Await.result(c, 3.seconds)
      println(r) // 205
    }

    'scala > scala3' 카테고리의 다른 글

    Either using cats and ox  (0) 2024.04.04
    play-json 에서 scala3 enum 사용하기  (0) 2024.03.29
    Exports  (0) 2024.03.22
    opaque type  (0) 2024.03.22
    typeclass  (0) 2024.03.22

    댓글

Designed by Tistory.