Stream.toList的实现(和文档)是这样的:
Collections.unmodifiableList(new ArrayList<>(Arrays.asList(this.toArray())))
Run Code Online (Sandbox Code Playgroud)
我想知道为什么需要将返回的列表Arrays.asList复制到新的ArrayList. 仅返回以下内容还不够吗?
Collections.unmodifiableList(Arrays.asList(this.toArray()))
Run Code Online (Sandbox Code Playgroud)
我想知道,如果我编写一个返回它创建的列表的方法,如果我不费心制作它的防御性副本,是否会出现任何问题?
当涉及到地图时,我对 Kotlin 的 null 安全功能感到困惑。我有一个Map<String, String>。但我可以打电话map.get(null),它会返回null以指示地图中不存在该钥匙。我预计会出现编译器错误,因为map是 aMap<String, String>而不是Map<String?, String>. 我怎么可以通过null争论String呢?
还有一个相关的问题:是否有任何类型的 Map,无论是 stdlib 还是第三方实现,NullPointerException如果我调用,可能会抛出异常get(null)?我想知道对于 的任何有效实现,调用map.get(s)而不是,是否安全。s?.let { map.get(it) }Map
更新
编译器确实返回了一个错误map.get(null)。但这并不是因为空安全,而是因为文字null没有向编译器指示所传递参数的类型。我的实际代码更像是这样的:
val map: Map<String, String> = ...
val s: String? = null
val t = map.get(s)
Run Code Online (Sandbox Code Playgroud)
上面的代码编译良好,并返回null. 当键应该是String不可空的时,为什么会这样呢?
Kotlin 中有没有一种方法可以“窥视”迭代器的下一个元素而不推进它?对于示例用例,请考虑此函数用于合并两个预排序的序列:
fun merge(seq1: Sequence<Int>, seq2: Sequence<Int>) = sequence<Int> {
val it1 = seq1.iterator()
var current1 = if (it1.hasNext()) it1.next() else null
val it2 = seq2.iterator()
var current2 = if (it2.hasNext()) it2.next() else null
while (current1 != null && current2 != null) {
if (current1 <= current2) {
yield(current1)
current1 = if (it1.hasNext()) it1.next() else null
} else {
yield(current2)
current2 = if (it2.hasNext()) it2.next() else null
}
}
while (current1 != null) {
yield(current1)
current1 = if (it1.hasNext()) it1.next() …Run Code Online (Sandbox Code Playgroud) 有没有办法捕获控制语句中流程的值when?
when(some expression) {
"one" -> println("two")
"two" -> println("three")
else -> println("Error: ${???} is not a recognised option.")
}
Run Code Online (Sandbox Code Playgroud)
我们应该如何得到上面 所代表的值{???}呢?
众所周知,并不是所有的十进制数都可以用二进制浮点数精确表示。
然而,似乎所有的二进制浮点数都可以用十进制表示法精确表示。
为什么没有任何浮点数不能用十进制表示,而反过来则不然呢?看起来有些不对称。
interface MyInterface {
default int someMethod() {
return 0;
}
int anotherMethod();
}
class Test implements MyInterface {
public static void main(String[] args) {
Test q = new Test();
q.run();
}
@Override
public int anotherMethod() {
return 1;
}
void run() {
MyInterface a = () -> someMethod();
System.out.println(a.anotherMethod());
}
}
Run Code Online (Sandbox Code Playgroud)
执行结果将为0,虽然我期望的是1。我不明白为什么不返回重写方法的结果,而是返回默认方法的结果。