What's the Scala syntax for a function taking any subtype of Ordered[A]?

孤者浪人 提交于 2019-12-03 10:40:04

The equivalent of Haskell's type classes in Scala is done via implicits. There are two ways to do what you want

The first is with view bounds

scala> def lessThan[T <% Ordered[T]](x : T, y : T) = x < y
lessThan: [T](T,T)(implicit (T) => Ordered[T])Boolean

scala> lessThan(1,2)
res0: Boolean = true

The second is with an implicit parameter

scala> def lessThan[T](x : T, y : T)(implicit f : T => Ordered[T]) = x < y      
lessThan: [T](T,T)(implicit (T) => Ordered[T])Boolean

scala> lessThan(4,3)
res1: Boolean = false

The former is syntax sugar for the later. The later allows more flexibility.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!