scala/basic
-
method 이름은 같은데 param, return 타입을 다르게 구현하기scala/basic 2024. 3. 7. 17:06
case class GoogleRaw(content: String, crawlId: String) case class NaverRaw(content: String) case class GoogleParsed(sections: Seq[String], crawlId: String) case class NaverParsed(sections: Seq[String]) trait Cralwer { type Raw type Parsed def fetch(url: String): Raw def parse(raw: Raw): Parsed def save(raw: Raw, parsed: Parsed): Int } object GoogleCrawler extends Cralwer { type Raw = GoogleRaw t..
-
Blocking Futurescala/basic 2023. 2. 13. 11:16
scala-best-practices 의 MUST use Scala's BlockContext on blocking I/O 문서와 SHOULD use a separate thread-pool for blocking I/O 를 참고했을 때, 간편하게 쓴다면 아래처럼 BlockingFuture Helper 를 만드는 것도 좋을 것 같다. import scala.concurrent.{blocking, Future, ExecutionContext} /** * This is an idiomatic way of executing blocking code * Use BlockingFuture(...) instead of normal Future(...) anywhere */ object BlockingFuture {..
-
Environment, Property variable 읽기scala/basic 2023. 2. 3. 15:34
Environment val myEnv: Option[String] = sys.env.get("MY_ENV") println(myEnv) > export MY_ENV="env_123" > java -cp app.jar ... Property val myProp: Option[String] = sys.props.get("MY_PROP") println(myProp) > java -cp app.jar -DMY_PROP="prop_abc" ...
-
Future[Try[A]] <=> Future[A] 상호간 변환하기scala/basic 2023. 1. 16. 12:58
Future[Try[A]] Future[A] 변환 Future[Try[A]] => Future[A] import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.util.{Success, Try} object FutureTryTest { def main(args: Array[String]): Unit = { val futureTry: Future[Try[Int]] = Future(Success(1)) // https://github.com/monix/monix/blob/series/3.x/monix-execution/shared/src/main/scala/monix/execution/..
-
Error Modeling (with Exception)scala/basic 2023. 1. 16. 10:55
import play.api.libs.json.{Json, OFormat} sealed class HttpError(val status: Int, val message: String) extends Throwable(message) object HttpError { implicit val jsonFormat: OFormat[HttpError] = Json.format[HttpError] def apply(status: Int, message: String): HttpError = new HttpError(status, message) def unapply(err: Throwable): Option[(Int, String)] = err match { case err: HttpError => Option((..
-
Scala Usingscala/basic 2022. 12. 19. 00:03
scala 2.13 버전부터 scala.util.Using 이 추가되었다. cats-effect 의 Resource 또는 zio 의 Scope 처럼 resource 관리를 위해 사용될 수 있다. AutoCloseable Resource 에서 사용 기본적으로 Using.resource(..) 혹은 Using.resources(..) 를 이용하자. (필요하면 Try 로 감싼다) https://www.scala-lang.org/api/2.13.6/scala/util/Using$$Releasable.html 을 보면 아래와 같은 내용이 있다. An instance of Releasable is needed in order to automatically manage a resource with Using. An ..
-
Scala Closurescala/basic 2022. 10. 21. 19:56
코드 object ScalaApp { def runner(f: () => Int): Unit = { val out = f() println(out) } def sum(x: Int, y: Int): () => Int = { val inner = () => x + y inner } def main(args: Array[String]): Unit = { val f = sum(1, 2) runner(f) } } 설명 python 의 Closure 와 비교해 보자