OhM*_*Mad 8 sorting list kotlin
我有这个令牌对象:
class Token(type: TokenType, value: String, position: IntRange = 0..0)
Run Code Online (Sandbox Code Playgroud)
我声明一个 MutableList:
val tokens: MutableList<Token> = mutableListOf()
// Mutable List filled
Run Code Online (Sandbox Code Playgroud)
现在我想根据位置 IntRange 的第一个值对我的列表进行排序。我尝试这样做:
tokens
.sortedBy { it.position.first }
Run Code Online (Sandbox Code Playgroud)
但是,使用 it 关键字后我无法访问该对象,因此位置以红色突出显示。
有什么建议?
Ily*_*lya 14
另一个观察结果是sortedBy返回列表的排序副本。如果你想对你的可变列表进行排序,你应该使用sortBy函数:
tokens.sortBy { it.position.first }
// tokens is sorted now
Run Code Online (Sandbox Code Playgroud)
这position是一个参数而不是属性,通过/关键字将其设置为主构造函数上的属性,例如:valvar
//makes the parameter to a property by `val` keyword---v
class Token(val type: TokenType, val value: String, val position:IntRange = 0..0)
Run Code Online (Sandbox Code Playgroud)
然后你可以按Tokens 排序position,例如:
tokens.sortedBy { it.position.first }
Run Code Online (Sandbox Code Playgroud)