理解`单形态'无形的例子

时间:2015-01-29 02:58:37

标签: scala shapeless

Shapeless Features Overview显示以下示例:

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)

但是,由于缺乏对Shapeless的经验,我不了解它与以下内容之间的区别:

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)

1 个答案:

答案 0 :(得分:9)

这里的重要区别是,choose是一个可以作为值传递的函数。您不能从f中创建(合理)值,因为Scala不支持多态函数值:

scala> val fun = f _
fun: Set[Nothing] => Option[Nothing] = <function1>

如您所见,Scala将元素类型修复为Nothing,使该函数对非空集无效:

scala> fun(Set(1))
<console>:10: error: type mismatch;
 found   : Int(1)
 required: Nothing
              fun(Set(1))
                      ^

这与您在Shapeless方法中所期望的一样。