函数toArray
应该将类型擦除列表转换T
为Array<String>
现在的列表.
inline fun <reified T> toArray(list: List<*>): T {
return list.toTypedArray() as T
}
toArray<Array<String>>(listOf("a", "b", "c")) // should be arrayOf("a", "b", "c")
Run Code Online (Sandbox Code Playgroud)
但是,toArray
抛出此错误.
java.lang.ClassCastException:[Ljava.lang.Object; 无法转换为[Ljava.lang.String;
你有什么想法?
这种方法很好.但是,我认为它不起作用.
fun getCopy(array: Array<BooleanArray>): Array<BooleanArray> {
val copy = Array(array.size) { BooleanArray(array[0].size) { false } }
for (i in array.indices) {
for (j in array[i].indices) {
copy[i][j] = array[i][j]
}
}
return copy
}
Run Code Online (Sandbox Code Playgroud)
有更多功能的方式吗?
我写了下面的代码来获得一个KClass Array<*>
.
Array::class
Run Code Online (Sandbox Code Playgroud)
但是,此代码有编译错误.
Kotlin:Array类文字需要一个类型参数,请在尖括号中指定一个
你知道原因还是解决方案?
我想投Any
给Int
用KClass<Int>
,有KClass<Int>
和Any
这实际上是Int
.
fun <T> cast(any: Any, clazz: KClass<*>): T = clazz.java.cast(any)
cast(0, Int::class)
Run Code Online (Sandbox Code Playgroud)
但是,我收到了这个错误.
java.lang.ClassCastException:无法将java.lang.Integer强制转换为int
你知道除了解决方案any as Int
吗?
这是使用 KotlinTest 1.3.5 的测试代码。
val expect = 0.1
val actual: Double = getSomeDoubleValue()
actual shouldBe expect
Run Code Online (Sandbox Code Playgroud)
并且在运行代码时打印了此警告。
[警告] 比较双打时考虑使用容差,例如:a shouldBe b plusOrMinus c
在这种情况下,我不想使用plusOrMinus
. 所以,我将代码固定为
val expect = 0.1
val actual: Double = getSomeDoubleValue()
actual shouldBe exactly(expect)
Run Code Online (Sandbox Code Playgroud)
现在,没有警告。
不过,我想知道的区别shouldBe
和shouldBe exactly
。它是什么?
Kotlin具有扩展功能run
.
/**
* Calls the specified function [block] and returns its result.
*/
@kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R = block()
Run Code Online (Sandbox Code Playgroud)
并且run
可以使用函数代替返回.
// an example multi-line method using return
fun plus(a: Int, b: Int): Int {
val sum = a + b
return sum
}
// uses run instead of return
fun plus(a: Int, b: Int): Int = run {
val sum = a + b
sum
}
Run Code Online (Sandbox Code Playgroud)
哪种款式更好?