Created
September 9, 2012 03:05
-
-
Save gclaramunt/3682353 to your computer and use it in GitHub Desktop.
Tagged Ids using Phantom types
This file contains hidden or 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
trait Entity | |
trait User extends Entity | |
trait Product extends Entity | |
case class Id[T<:Entity](id:String) | |
def buy(pId:Id[Product],uId:Id[User])="Bought product %s for user %s".format(pId.id,uId.id) | |
val pId=new Id[Product]("1") | |
val uId=new Id[User]("2") | |
/* | |
scala> buy(pId,uId) | |
res2: String = Bought product 1 for user 2 | |
scala> buy(uId,pId) | |
<console>:16: error: type mismatch; | |
found : Id[User] | |
required: Id[Product] | |
buy(uId,pId) | |
^ | |
*/ |
This file contains hidden or 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
/* | |
In Java due to popular request | |
*/ | |
public interface Entity{ | |
} | |
public interface User extends Entity{ | |
} | |
public interface Product extends Entity{ | |
} | |
public class Id<T extends Entity>{ | |
private String id; | |
public Id(String id){ | |
this.id=id; | |
} | |
public String getId(){ | |
return id; | |
} | |
} | |
public class Buyer { | |
public static String buy(Id<Product> pId, Id<User> uId){ | |
return "Bought product "+pId.getId()+" for user "+uId.getId(); | |
} | |
public static void main(String[] args){ | |
Id<Product> pId=new Id<Product>("1"); | |
Id<User> uId=new Id<User>("2"); | |
System.out.println(buy(pId,uId)); | |
/* | |
Doesn't compile | |
System.out.println(buy(uId,pId)); | |
*/ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment