小编Jos*_*ses的帖子

TreeSet在映射后不遵守顺序

我不知道如何解释/理解有关TreeSet和map函数的以下行为.

我想我在拼图中错过了一块.对此事的任何启示都将受到欢迎.

scala> class Person(val name: String, val age: Int) extends Ordered[Person]{
     |   def compare(that: Person) = {
     |     val nameComparison = name.compareToIgnoreCase(that.name)
     |     if(nameComparison != 0){
     |       nameComparison
     |     }else{
     |       age.compareTo(that.age)
     |     }
     |   }
     |   override def toString = s"$name || $age"
     | }
defined class Person

scala> import scala.collection.immutable.TreeSet
import scala.collection.immutable.TreeSet

scala> val tsPersons = TreeSet(
     |   new Person("Vivi", 31),
     |   new Person("ViVi", 4),
     |   new Person("vivi", 14)
     | )//1) printed in expected order
tsPersons: scala.collection.immutable.TreeSet[Person] …
Run Code Online (Sandbox Code Playgroud)

scala map treeset

1
推荐指数
1
解决办法
224
查看次数

用def定义函数

试试repl:

scala> def add(x: Int) = 1 + x
add: (x: Int)Int

scala> add(2)
res0: Int = 3

scala> def add = (x: Int) => 1 + x
add: Int => Int

scala> add(2)
res1: Int = 3
Run Code Online (Sandbox Code Playgroud)

我看到"添加"定义在repl打印的类型上有所不同.我猜第一个定义类似于方法,第二个定义类似于函数值.

以某种方式定义添加有什么区别?这是一种更好或沮丧的方式吗?

谢谢您的帮助.

scala function

0
推荐指数
1
解决办法
68
查看次数

标签 统计

scala ×2

function ×1

map ×1

treeset ×1