The 无形特征概述 https://github.com/milessabin/shapeless/wiki/Feature-overview%3a-shapeless-2.0.0显示以下示例:
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)
这里重要的区别是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 方法所期望的那样。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)