Skip to content

Instantly share code, notes, and snippets.

@gclaramunt
Created September 9, 2012 03:05
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gclaramunt/3682353 to your computer and use it in GitHub Desktop.
Save gclaramunt/3682353 to your computer and use it in GitHub Desktop.
Tagged Ids using Phantom types
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)
^
*/
/*
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