无法比较max函数中的Long

时间:2014-04-22 14:49:41

标签: scala

我正在Scala中编写max函数:

scala> def max[Long](xs: List[Long]): Long = 
        xs.foldLeft(Long.MinValue){ (acc, elem) => if(elem > acc) elem else acc}

但它给了我这些编译时错误。查看长docs,此对象显然具有MinValue方法。此外,Long当然可以相互比较。

<console>:7: error: value > is not a member of type parameter Long
       def max[Long](xs: List[Long]): Long = 
         xs.foldLeft(Long.MinValue){ (acc, elem) => if(elem > acc) elem else acc}

<console>:7: error: type mismatch;
 found   : Long(in method max)
 required: scala.Long
       def max[Long](xs: List[Long]): Long = 
          xs.foldLeft(Long.MinValue){ (acc, elem) => if(elem > acc) elem else acc}

<console>:7: error: type mismatch;
 found   : scala.Long
 required: Long(in method max)
       def max[Long](xs: List[Long]): Long = 
         xs.foldLeft(Long.MinValue){ (acc, elem) => if(elem > acc) elem else acc}
                                                                   ^

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您的方法不是通用的,因此您不需要type参数:

def max(xs: List[Long]): Long = 
        xs.foldLeft(Long.MinValue){ (acc, elem) => if(elem > acc) elem else acc}

通用参数名称Long正在为列表和返回类型隐藏scala.Long类型,因此您的签名与以下内容相同:

def max[A](xs: List[A]): A

请注意,您也可以使用max方法:

def max(xs: List[Long]): Long = xs.foldLeft(Long.MinValue){(acc, elem) => acc.max(elem)}