指定内联隐式排序的正确方法

huangapple go评论55阅读模式
英文:

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)

或者在定义站点定义默认的OrderingEmployee数据类型的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

huangapple
  • 本文由 发表于 2023年2月23日 21:28:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545513.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定