我正在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}
^
我做错了什么?
答案 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)}