Tag: 类型转换

在Kotlin的Double.toInt()中使用哪种方法舍入或截断?

在官方的API文档上 ,它说: 以Int形式返回此数字的值,可能涉及四舍五入或截断。 我想截断,但不知道。 任何人都可以解释may involve rounding or truncation的确切含义吗? ps:在我的单元测试中, (1.7).toInt()是1, 可能涉及截断。

转换容器类型?

也许我错过了一些显而易见的东西……在整个文档中,我认为Kotlin有各种各样的序列,这些序列是不能互操作的。 即使复制一个序列效率低下 – 当我需要将它传递给一个语义相同但类型不同的函数时,这是无法帮助的。 所以我想出了这些构造函数和转换器(仅用于Int和一种方式): fun IntArray(a: Array<Int>) = IntArray( a.size ) { a[it] } fun IntArray(c: Collection<Int>) = IntArray( c.size ) { c.elementAt(it) } fun IntArray(p: IntProgression) = IntArray( p.toList() ) fun IntArray(s: Sequence<Int>) = IntArray( s.toList() ) fun Array<Int>.toIntArray() = IntArray( this ) fun Collection<Int>.toIntArray() = IntArray( this ) fun IntProgression.toIntArray() = IntArray( […]

kotlin – 数字类型的自动转换

在Java中 ,我们可以将int赋值为double ,例如double x = 123 ; 在kotlin ,我们得到了一个编译错误。 问题:我们可以在kotlin启用自动转换功能吗? 为什么kotlin默认没有这个功能? var x: Double = 123; // ERROR 再举一个例子: fun foo(x: Double) { } fun main(args: Array<String>) { foo(123.0); // OK foo(123); // ERROR } 更新: 文字123可以在编译时自动转换为Short或Long 。 但它不会被转换为Float或Double 。 fun fooShort(x: Short) {} fun fooInt(x: Int) {} fun fooLong(x: Long) {} fun main(args: Array<String>) […]