Skip to content

Instantly share code, notes, and snippets.

View ChaingFuture.sc
import java.time.Instant
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
case class UserInfo(userId: Int, nickname: String, emailAddress: String, account: Option[Long])
def getNicknameById(userId: Int): Future[String] = Future {
Thread.sleep(2000)
View UserApplicative.sc
/**
* Use cats applicative
*/
import cats.syntax.all._
import cats.instances.future._
val start3: Instant = Instant.now
val fUserInfo3 = for {
View CallFirstAndUseNext.sc
/**
* Calling first and use next
*/
def getEmailAndAccountTuple(fNickname: Future[String]): Future[(String, Option[Long])] =
fNickname.flatMap(nickname => {
val fEmailAddr = getEmailAddressByNickname(nickname)
val fAccountInfo = getAccountInfoByNickname(nickname)
fEmailAddr.flatMap(email => fAccountInfo.map(account => (email, account)))
View useByForComprehension.sc
/**
* Just use for comprehension
*/
val start1: Instant = Instant.now
val fUserInfo1 = for {
nickname <- getNicknameById(userId)
emailAddr <- getEmailAddressByNickname(nickname)
accountInfo <- getAccountInfoByNickname(nickname)
View simulation.sc
case class UserInfo(userId: Int, nickname: String, emailAddress: String, account: Option[Long])
def getNicknameById(userId: Int): Future[String] = Future {
Thread.sleep(2000)
"ktz"
}
def getEmailAddressByNickname(nickname: String): Future[String] = Future {
Thread.sleep(2000)
"helloworld@example.com"
View ImplicitInstanceInCompanionObject.sc
case class Hello(value: String)
trait Printer[T] {
def print(value: T): String
}
object Printer {
implicit val IntPrinter: Printer[Int] = new Printer[Int] {
override def print(value: Int): String = s"Type: Int - $value"
}
View ImplicitOrder.scala
object ImplicitOrder extends App{
implicit val implicitIntInstance1: Instance[String] = Instance("Implicit Instance in Same Conjure")
def getString(implicit implicitInstance: Instance[String]): String = implicitInstance.value
import Imported.implicitIntInstance1
println(getString)
}
case class Instance[T](value: T)
View ImplicitVal.sc
def print(implicit printableClass: PrintableClass): Unit = {
println(printableClass.print)
}
implicit val printableClass = PrintableClass("Implicit Val")
print
View ImplicitClass.sc
implicit class ConvertableValueCaseClass(valueCaseClass: ValueCaseClass) {
def toPrintable: PrintableClass = PrintableClass(valueCaseClass.value)
}
val printableClass2: PrintableClass = ValueCaseClass("Implicit class").toPrintable // by using implicit class
println(printableClass2.print)
View ImplicitDef.sc
implicit def convertValueCaseClassToPrintable(valueCaseClass: ValueCaseClass): PrintableClass =
PrintableClass(valueCaseClass.value)
val printableClass: PrintableClass = ValueCaseClass("Implicit Def") // by using convertValueCaseClassToPrintable
println(printableClass.print)
You can’t perform that action at this time.