英文:
Correct way to specify inline implicit ordering
问题
case class Employee(name: String, id: Int)
然后,我想指定内联的隐式排序,如下所示:
es.sorted(implicit ord: Ordering[Employee] = Ordering.by(_.name))
这段代码不起作用。
有什么正确的方法可以实现这个需求?
英文:
Let's say I've got a case class definition:
// Scala 2.13
case class Employee(name: String, id: Int)
Then I'd like to specify an inline implicit ordering like:
es.sorted(implicit ord: Ordering[Employee] = Ordering.by(_.name))
which doesn't work.
What could be a correct way to do that?
答案1
得分: 2
尝试在调用站点明确指定Ordering
case class Employee(name: String, id: Int)
es.sorted[Employee](Ordering.by(_.name))
// es.sorted(Ordering.by((_: Employee).name))
// es.sortBy(_.name)
或者在定义站点定义默认的Ordering
(Employee
数据类型的Ordering
类型类的实例)
case class Employee(name: String, id: Int)
object Employee {
implicit val employeeOrdering: Ordering[Employee] = Ordering.by(_.name)
}
es.sorted
英文:
Try to specify Ordering
explicitly at a call site
case class Employee(name: String, id: Int)
es.sorted[Employee](Ordering.by(_.name))
// es.sorted(Ordering.by((_: Employee).name))
// es.sortBy(_.name)
or define default Ordering
at the definition site (an instance of the type class Ordering
for the data type Employee
)
case class Employee(name: String, id: Int)
object Employee {
implicit val employeeOrdering: Ordering[Employee] = Ordering.by(_.name)
}
es.sorted
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论