Skip to content

Instantly share code, notes, and snippets.

@shankarshastri
Last active October 23, 2020 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shankarshastri/6315a3c148c892179e03e3e44663d1f1 to your computer and use it in GitHub Desktop.
Save shankarshastri/6315a3c148c892179e03e3e44663d1f1 to your computer and use it in GitHub Desktop.
Learning Scala3
object ExploreDependentFunctionValue {
trait Entry { type Key; val key: Key }
def extractKey(e: Entry): e.Key = e.key // a dependent method
val extractor: (e: Entry) => e.Key = extractKey // a dependent function value
final case class IntEntry() extends Entry {
type Key = Int
override val key = 10
}
@main
def m = {
println(extractKey(IntEntry()))
println(extractor(IntEntry()))
}
}
object ExploreIntersectionTypes {
trait Mapper[A, B] {
def map(l: List[A])(f: A => B): List[B] = l.map(f)
}
trait Reducer[A, B >: A] {
def reduce(l: List[A])(f: (B, B) => B): B = l.reduce(f)
}
def mapAndReduce[A, B, C >: B](mR: Mapper[A, B] & Reducer[B, C], l: List[A])(
mapFuncf: A => B
)(reduceFuncf: (C, C) => C): C = {
mR.reduce(mR.map(l)(mapFuncf))(reduceFuncf)
}
val multBy2: Int => Int = (e: Int) => e * 2
val reduceToSum: (Int, Int) => Int = (a: Int, b: Int) => (a + b)
case class MapperAndReducer[A, B, C >: B]()
extends Mapper[A, B]
with Reducer[B, C]
@main
def m: Unit = {
println(
mapAndReduce(MapperAndReducer[Int, Int, Int](), List(1, 2, 3))(multBy2)(
reduceToSum
)
)
}
}
object ExploreMatchTypes {
type Elem[X] = X match {
case String => Char
case Array[t] => t
case Iterable[t] => t
}
@main
def m = {
val char: Elem[String] = 'H'
val elementOfArray: Elem[Array[Int]] = 10
val elementOfList: Elem[List[Int]] = 20
println(char)
println(elementOfArray)
println(elementOfList)
}
}
object ExploreTypeLambdas {
final case class Some[T](t: T)
final case class None()
type OptionWithTypeLambdas = [T] =>> (Some[T] | None)
type OptionWithoutTypeLambdas[T] = Some[T] | None
def toOptionWithTypeLambdas[T](t: T): OptionWithTypeLambdas[T] = {
if (t == null) None() else Some(t)
}
def toOptionWithoutTypeLambdas[T](t: T): OptionWithoutTypeLambdas[T] = {
if (t == null) None() else Some(t)
}
@main
def m = {
println(toOptionWithTypeLambdas(null))
println(toOptionWithoutTypeLambdas(null))
}
}
object ExploreUnionTypes {
final case class Some[T](t: T)
final case class None()
type Option[T] = Some[T] | None
def toOption[T](t: T): Option[T] = {
if (t == null) None() else Some(t)
}
@main
def m = {
println(toOption("J"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment