Skip to content

Instantly share code, notes, and snippets.

@neilchaudhuri
Last active March 29, 2019 23:51
Show Gist options
  • Save neilchaudhuri/6102b1fd9539d18fc918d7a872b90a03 to your computer and use it in GitHub Desktop.
Save neilchaudhuri/6102b1fd9539d18fc918d7a872b90a03 to your computer and use it in GitHub Desktop.
Examples of idiomatic Scala polymorphism
// Runtime polymorphism
trait Closeable {
def name: String
def close: String
}
case class Connection(override val name: String, database: String) extends Closeable {
override def close: String = s"Closing connection $name"
}
case class File(override val name: String, opener: String) extends Closeable {
override def close: String = s"Closing file $name"
}
def showClosing(c: Closeable): String = c.close
val w = Connection("MyConnection", "PostgreSQL")
val f = File("file.txt", "TextEdit")
showClosing(w)
showClosing(f)
// Parameteric polymorphism (generics) with List[T]
val numbers = List(1, 2, 3)
val firstNumber: Int = numbers.head
val strings = List("1", "2", "3")
val firstString: String = strings.head
def use[T <: File](t: T) = s"Using ${t.name}"
use(f)
// Typeclass polymorphism
case class Complex(real: Double, imaginary: Double)
object Complex {
implicit object ComplexOrdering extends Ordering[Complex] {
def compare(a: Complex, b: Complex): Int = a.real.compare(b.real)
}
}
List(Complex(3, 5), Complex(10, 2), Complex(1, 6)).sorted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment