Skip to content

Instantly share code, notes, and snippets.

@jedahu
Last active August 25, 2016 06:56
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 jedahu/1b8808f797de1909ac95371eaf1ed97b to your computer and use it in GitHub Desktop.
Save jedahu/1b8808f797de1909ac95371eaf1ed97b to your computer and use it in GitHub Desktop.
Get Typed (Scala)
package gettyped
sealed abstract class Maybe[A] {
def fold[B](nothing: => B, just: A => B): B = this match {
case Nothing() => nothing
case Just(a) => just(a)
}
}
private final case class Nothing[A]() extends Maybe[A] {}
private final case class Just[A](a: A) extends Maybe[A] {}
object Maybe {
def nothing[A]: Maybe[A] = Nothing()
def just[A](a: A): Maybe[A] = Just(a)
}
object ScalaJSExample extends js.JSApp {
def main(): Unit = {
println("Compile success")
}
}
// See https://gettyped.github.io/type/Maybe.html
package gettyped
sealed abstract class Maybe[A] {
def fold[B](nothing: => B, just: A => B): B = this match {
case Nothing() => nothing
case Just(a) => just(a)
}
}
private final case class Nothing[A]() extends Maybe[A] {}
private final case class Just[A](a: A) extends Maybe[A] {}
object Maybe {
def nothing[A]: Maybe[A] = Nothing()
def just[A](a: A): Maybe[A] = Just(a)
}
object ScalaJSExample extends js.JSApp {
import Maybe._
final case class Name(first: String, last: String)
val absent: String = "Nobody"
def present(n: Name): String = s"${n.first} ${n.last}"
def describe(n: Maybe[Name]): String =
n.fold(absent, present)
/// Uncomment `describeT` and this file will fail to compile.
// def describeT(n: Maybe[Name]): String =
// n.fold(present, absent)
val names: List[Maybe[Name]] =
List(
just(Name("Jane", "Doe")),
nothing,
just(Name("John", "Doe")))
def main(): Unit = {
println("describe")
names.foreach { n => println(describe(n)) }
}
}
// See https://gettyped.github.io/type/Maybe.html
package gettyped
sealed abstract class Maybe[A] {
def fold[B](nothing: => B, just: A => B): B = this match {
case Nothing() => nothing
case Just(a) => just(a)
}
}
private final case class Nothing[A]() extends Maybe[A] {}
private final case class Just[A](a: A) extends Maybe[A] {}
object Maybe {
def nothing[A]: Maybe[A] = Nothing()
def just[A](a: A): Maybe[A] = Just(a)
}
object ScalaJSExample extends js.JSApp {
final case class Name(first: String, last: String)
val absent: String = "Nobody"
def present(n: Name): String = s"${n.first} ${n.last}"
def describe(n: Name): String =
if (n == null) absent else present(n)
def describeT(n: Name): String =
if (n == null) present(n) else absent
val names: List[Name] =
List(
Name("Jane", "Doe"),
null,
Name("John", "Doe"))
def main(): Unit = {
println("describe")
names.foreach { n => println(describe(n)) }
println("........")
println("describeT")
names.foreach { n => println(describeT(n)) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment