ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Function Context
    scala/scala3 2024. 4. 12. 17:00

    https://blog.softwaremill.com/context-is-king-20f533474cb3 에 자세히 설명되어 있다.

    아래는 내가 만들어 본 예제: function context 를 이용한 dependency injection

    import scala.concurrent.{Await, ExecutionContext, Future}
    
    case class Nami(x: Int)
    
    object ContextFunction {
      def f()(using executionContext: ExecutionContext): Future[Int] = Future {
        1 * 2
      }
    
      def g(y: Int)(using nami:Nami, executionContext: ExecutionContext): Future[Int] = Future { nami.x + y }
    
    
      def main(args: Array[String]): Unit = {
        // composition 이 되면서 Tuple 로 표현 가능함!
        val r: (ExecutionContext, Nami) ?=> Future[Int] = for {
          a <- f()
          b <- g(a)
        } yield b
    
    
        given ExecutionContext = scala.concurrent.ExecutionContext.global
        given Nami = Nami(10)
    
        val y = Await.result(r, scala.concurrent.duration.Duration.Inf)
        println(y)
      }
    }

     

    consturctor dependency injection 말고도 context dependency injection  이 있다면 각각은 어제 사용해야 할까?

    개인적으로 아래 처럼 생각해 봤다.

     

    • Function context: low level components 의존성 관리 (예: DB connection, apache spark instance, ...)
    • Constructor dependency injection:  high level components 의존성 관리 (서비스간 의존성)

     

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

    type lambdas  (0) 2024.04.23
    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

    댓글

Designed by Tistory.