加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

泛型 – 返回两个值中的第一个的通用方法

发布时间:2020-12-16 19:21:13 所属栏目:安全 来源:网络整理
导读:我需要一个方法来返回两个有序值中的第一个.我试过了: def first[T : Ordered[T]](a: T,b: T) = { a compare b match { case -1 | 0 = a case 1 = b }} 但得到 scala first(3,4)console:9: error: inferred type arguments [Int] do not conform to method
我需要一个方法来返回两个有序值中的第一个.我试过了:

def first[T <: Ordered[T]](a: T,b: T) = {
  a compare b match {
    case -1 | 0 => a
    case 1      => b
  }
}

但得到

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)
       ^

我想这是因为Int需要转换为RichInt,它是Ordered [Int]而不是Ordered [RichInt].接下来是什么?

解决方法

您可以使用类型类Ordering和context bound:

def first[T : Ordering](a: T,b: T) = {
  implicitly[Ordering[T]].compare(a,b) match {
    case -1 | 0 => a
    case 1      => b
  }
}

更新

如果导入scala.math.Ordered._,则可以进一步简化此代码. Companion object of Ordered有orderedToOrdered隐式转换,因此具有Ordering的所有内容也将被视为Ordered:

import scala.math.Ordered._

def first[T : Ordering](a: T,b: T) = if (a <= b) a else b

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读