Created
February 7, 2017 04:26
-
-
Save rohinp/b1ef05a0fac40023249ad4fec35bbcb7 to your computer and use it in GitHub Desktop.
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
//simple addition operation, nothing to explain in this v1 | |
def add(a: Int, b: Int): Int = a + b | |
//Lets make version v1 polymorphic | |
//below code will fail as the type A may or may not have an + operation | |
def add[A](a: A, b: A): A = a + b | |
//so we need a trait which can define that operation for us | |
trait Num[A] { | |
def +(a: A, b: A): A | |
} | |
//modified add function in v2 | |
def add[A](a: A, b: A)(implicit n:Num[A]): A = n.+(a, b) | |
//modified to use type bound this is our version v3 | |
def add[A: Num](a: A, b: A): A = implicitly[Num[A]].+(a, b) | |
//implimenting the trait | |
implicit object NumInt extends Num[Int] { | |
def +(a: Int, b: Int): Int = a + b | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment