问题描述
我需要一种方法来返回两个有序值中的第一个值。我试过:
def first [T<:Ordered [T]](a:T,b:T) = {
a比较b匹配{
case -1 | 0 =>
情况1 => b
code>
但是获得
scala>第一个(3,4)
< console>:9:错误:推断类型参数[Int]不符合方法第一个
类型参数bounds [T<:Ordered [T]]
先(3,4)
^
我猜这是因为<$ c需要将$ c> Int 转换为 RichInt ,这是 Ordered [Int] 而不是 Ordered [RichInt] 。下一步是什么?
您可以使用类型 Ordering :
def first [T:Ordering](a:T,b:T)= {
implicitly [Ordering [T]]。比较(a,b)匹配{
case -1 | 0 =>
情况1 => b
$ b code
$ b $ h3更新
如果您< import scala.math.Ordered ._ ,则可以进一步简化此代码。 有 orderedToOrdered 隐式转换,因此所有包含 Ordering 的内容也将被视为 Ordered :
import scala.math.Ordered._
def第一个[T:排序](a:T,b:T)= if(a
I need a method to return the first of two ordered values. I've tried:
def first[T <: Ordered[T]](a: T, b: T) = { a compare b match { case -1 | 0 => a case 1 => b } }but get
scala> first(3,4) <console>:9: error: inferred type arguments [Int] do not conform to method first's type parameter bounds [T <: Ordered[T]] first(3,4) ^I guess this is because Int needs to be converted to a RichInt, which is an Ordered[Int] rather than an Ordered[RichInt]. What next?
解决方案You can use type class Ordering and context bound:
def first[T : Ordering](a: T, b: T) = { implicitly[Ordering[T]].compare(a, b) match { case -1 | 0 => a case 1 => b } }Update
This code can be simplified further if you import scala.math.Ordered._. Companion object of Ordered has orderingToOrdered implicit conversion, so everything that has Ordering would also be treated as Ordered:
import scala.math.Ordered._ def first[T : Ordering](a: T, b: T) = if (a <= b) a else b
这篇关于通用方法返回两个值中的第一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!