Skip to content

Instantly share code, notes, and snippets.

View deanwampler's full-sized avatar

Dean Wampler deanwampler

View GitHub Profile
trait Transaction(database: DB):
def begin(query: String): Either[String,Status]
def rollback(): Either[String,Status]
def commit(): Either[String,Status]
trait ConnectionManager(database: DB):
def createTransaction: Transaction
def doTransaction(query: => String)(
using cm: => ConnectionManager): Seq[Status] = ...
scala> import scala.language.strictEquality // Enable the language feature
scala> enum Tree[T] derives CanEqual: // A type hierarchy that derives CanEqual
| case Branch(left: Tree[T], right: Tree[T])
| case Leaf(elem: T)
// defined class Tree
scala> import Tree.*
scala> val l1 = Leaf("l1")
scala> import scala.annotation.targetName
scala> trait Semigroup[T]: // also used in other examples for Type Classes
| extension (t: T)
| infix def combine(other: T): T
| @targetName("plus") def <+>(other: T): T = t.combine(other)
|
| trait Monoid[T] extends Semigroup[T]:
| def unit: T
case class U1[+T](t: T)
case class U2[+T](t: T)
def f1[T1,T2](name: String)(using u1: U1[T1])(using u2: U2[T2]): String =
s"f1: $name: $u1, $u2"
def f2[T1,T2](name: String)(using u1: U1[T1])(u2: U2[T2]): String =
s"f2: $name: $u1, $u2"
given u1i: U1[Int] = U1[Int](0)
given u2s: U2[String] = U2[String]("one")
// Compare to scala2-3-MonoidTypeClassNumeric2.scala
// Anonymous givens; just remove the name!
given [T](using num: Numeric[T]): Monoid[T] with
def unit: T = num.zero
extension (t: T) def combine(other: T): T = num.plus(t, other)
// or use the _context bound_ syntax:
// given [T: Numeric]: Monoid[T] with
// def unit: T = summon[Numeric[T]].zero // Use summon to retrieve the Numeric
// extension (t: T) def combine(other: T): T = summon[Numeric[T]].plus(t, other)
scala> Service.isAuthenticated
| Service.authenticate(UserName("Buck Trends"), Password("1234"))
| Service.isAuthenticated
|
val res8: Boolean = false
val res9: Boolean = true
val res10: Boolean = true
// Adapted from Programming Scala, Third Edition code repo:
// https://github.com/deanwampler/programming-scala-book-code-examples/blob/master/src/script/scala/progscala3/basicoop/Exports.scala
import java.net.URL
case class UserName(value: String):
assert(value.length > 0)
case class Password(value: String):
assert(value.length > 0)
scala> val o1 = Option.Some(1)
val o1: Option[Int] = Some(1) // Note the inferred types for all four cases.
scala> val o2 = Option.None
val o2: Option[Nothing] = None
scala> import Option._
scala> val o3 = Some(1)
val o3: Some[Int] = Some(1)
enum Option[+T]:
case Some(x: T)
case None
enum Option2[+T]:
case Some(x: T) extends Option2[T]
case None extends Option2[Nothing]
scala> trait Logger:
| def log(message: String): Unit
scala> val info = new Logger:
| def log(message: String): Unit = println(s"INFO: $message")
val info: Logger = anon$1@16f19cc9
scala> info.log("Hello world!")
INFO: Hello world!