Phantom Types

83 views
Skip to first unread message

Kevin Meredith

unread,
Jan 12, 2016, 11:42:22 AM1/12/16
to Typelevel Users & Development List
After reading the helpful, accepted answer on http://stackoverflow.com/questions/28247543/motivation-behind-phantom-types, I attempted to create a Phantom Type in Scala:

scala> case class Foo[A](x: Int)
defined class Foo

scala> def add(foo: Foo[Int], foo2: Foo[Int]): Int = foo.x + foo2.x
add: (foo: Foo[Int], foo2: Foo[Int])Int

scala> add(Foo[Int](1), Foo[Int](2))
res9: Int = 3

Note that I tried to add a `Foo[Int]` and `Foo[Double]`, but got a compile-time error, as expected:

scala> add(Foo[Int](1), Foo[Double](2))
<console>:15: error: type mismatch;
 found   : Foo[Double]
 required: Foo[Int]
       add(Foo[Int](1), Foo[Double](2))
                                   ^

Is my above `Foo` a correctly implemented Phantom Type? 

If so, must Foo's `A` be invariant to maintain it as a Phantom Type? 

christi...@gmail.com

unread,
Jan 14, 2016, 7:56:51 AM1/14/16
to Typelevel Users & Development List

Stephen Compall

unread,
Jan 15, 2016, 11:03:43 AM1/15/16
to Typelevel Users & Development List
Yes, it's a phantom type.

No, it doesn't have to be invariant, but it usually helps preserve the API you want.
Reply all
Reply to author
Forward
0 new messages