我正在查看数组扩展函数,发现了reduce()一个
inline fun <S, T: S> Array<out T>.reduce(operation: (acc: S, T) -> S): S {
if (isEmpty())
throw UnsupportedOperationException("Empty array can't be reduced.")
var accumulator: S = this[0]
for (index in 1..lastIndex) {
accumulator = operation(accumulator, this[index])
}
return accumulator
}
Run Code Online (Sandbox Code Playgroud)
这里的accumulator类型变量S分配有类型数组中的第一个元素T。
我无法理解reduce()具有两种数据类型的函数的真实用例。这里综合的例子实际上没有任何意义。
open class A(var width: Int = 0)
class B(width: Int) : A(width)
val array = arrayOf(A(7), A(4), A(1), A(4), A(3))
val res = array.reduce { acc, s …Run Code Online (Sandbox Code Playgroud) 我创建了简单的代码来反转等式,但lint在 IntelliJ IDEA中突出显示了两行。确切的消息是
对“子串”的调用是多余的
final String equation = "20+3*475-2-1*4";
final int size = equation.length();
final StringBuilder sb = new StringBuilder(size);
int right = size;
for (int i = size - 1; i > -1; i--) {
switch (equation.charAt(i)) {
case '+': case '-': case '*':
sb.append(equation.substring(i + 1, right)); // this line
sb.append(equation.charAt(i));
right = i;
}
}
if (right != 0) {
sb.append(equation.substring(0, right)); // and this line
}
Run Code Online (Sandbox Code Playgroud)
我从未遇到lint过无缘无故突出显示某些内容的情况。但是现在不知道为什么这些调用是多余的。
我已经创建了样本类来测试Kotlin中的断言
class Assertion {
fun sum(a: Int, b: Int): Int {
assert(a > 0 && b > 0)
return a + b
}
}
fun main(args: Array<String>) {
Assertion().sum(-1, 2)
}
Run Code Online (Sandbox Code Playgroud)
并使用以下选项,但该程序不会抛出断言异常.
-ea:AssertionKt,-ea:Assertion和-ea:...
当我尝试创建以下代码时:
class SmartCast {
var array: MutableList<Int>? = null
fun processArray() {
if (array != null && !array.isEmpty()) {
// process
}
}
}
Run Code Online (Sandbox Code Playgroud)
显示此错误:
无法智能地强制将其强制转换为“ MutableList”,因为“数组”是一个可变属性,到那时可能已经更改了
显然,在多线程的情况下,array可以将变量更改为null。但是,如果使用@Synchronized批注,则无法在array != null和之间对变量进行突变!array.isEmpty()。
@Synchronized
fun processArray() {
Run Code Online (Sandbox Code Playgroud)
我想知道为什么编译器不允许在同步块中进行智能转换,或者也许可以指定我的应用程序仅设计用于单线程模式?
更新:根据答案,我以以下方式更改了代码:
fun processArray() {
array?.takeUnless { it.isEmpty() }?.also {
for (elem in it)
// process elements
}
}
Run Code Online (Sandbox Code Playgroud)