The Shapeless Features Overview shows the following example:
import poly._
// choose is a function from Sets to Options with no type specific cases
object choose extends (Set ~> Option) {
def apply[T](s : Set[T]) = s.headOption
}
scala> choose(Set(1, 2, 3))
res0: Option[Int] = Some(1)
scala> choose(Set('a', 'b', 'c'))
res1: Option[Char] = Some(a)
However, I don't, in m lack of experience with Shapeless, understand the difference between that and the following:
scala> def f[T](set: Set[T]): Option[T] = set.headOption
f: [T](set: Set[T])Option[T]
scala> f( Set(1,2,3) )
res0: Option[Int] = Some(1)
scala> f( Set('a', 'b', 'c') )
res1: Option[Char] = Some(a)
The important difference here is, that choose
is a function that can be passed around as value. You cannot make a (reasonable) value out of f
, since Scala does not support polymorphic function values:
scala> val fun = f _
fun: Set[Nothing] => Option[Nothing] = <function1>
As you see, Scala fixes the element type to Nothing
rendering the function useless for non-empty sets:
scala> fun(Set(1))
<console>:10: error: type mismatch;
found : Int(1)
required: Nothing
fun(Set(1))
^
This works as you would expect with the Shapeless approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With