有没有一种方法可以在Kotlin中使用Initializator函数构造HashSet? [英] Is there a way to construct a HashSet with initializator function in Kotlin?
问题描述
要从 Facebook黑客杯2016年 Boomerang Constellations问题中的文件中读取星星,可以定义以下扩展功能:
To read Stars from a file in the Facebook Hacker Cup's 2016 Boomerang Constelations problem, following extension function can be defined:
fun BufferedReader.readStars(n: Int): Set<Star> {
return Array(n) {
val (l1, l2) = readLine().split(" ").map { it.toInt() }
Star(l1, l2)
}.toHashSet()
}
代码紧凑,但是首先将值读入数组,然后转换为HashSet
.有没有办法直接用Kotlin初始化大小为n
的HashSet
和Initializator函数?
Code is compact but the values are first read into an array and then converted to a HashSet
. Is there a way to directly initialize a HashSet
with the size of n
and initializator function in Kotlin?
更新:标准Kotlin库中是否存在现有方式?
UPDATE: Is there an existing way in standard Kotlin libs?
推荐答案
您始终可以使用apply
就地初始化对象:
You can always use apply
to initialize objects in-place:
HashSet<Star>(n).apply {
repeat(n) {
val (l1, l2) = readLine()!!.split(' ').map { it.toInt() }
put(Star(l1, l2))
}
}
如果每次输入都不太方便,请编写扩展功能:
If that's too inconvenient too type every time, write an extension function:
inline fun <T> createHashSet(n : Int, crossinline fn: (Int) -> T) = HashSet<T>(n).apply {
repeat(n) { add(fn(it)) }
}
用法:
createHashSet<Star>(n) {
val (l1, l2) = readLine()!!.split(' ').map { it.toInt() }
Star(l1, l2)
}
这篇关于有没有一种方法可以在Kotlin中使用Initializator函数构造HashSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!