Last active
March 29, 2019 23:51
-
-
Save neilchaudhuri/6102b1fd9539d18fc918d7a872b90a03 to your computer and use it in GitHub Desktop.
Examples of idiomatic Scala polymorphism
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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