我想做这样的事情:
fun process(minutes: Int) = 0
fun test() {
process(System.currentTimeMillis() / 1000 / 60) // error: Int expected
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试,process((System.currentTimeMillis() / 1000 / 60) as Int)我会ClassCastException在运行时获得.
那么如何将Long转换为Int?
Ale*_*øld 48
用途Long.toInt():
process((System.currentTimeMillis() / 1000 / 60).toInt())
Run Code Online (Sandbox Code Playgroud)
\xe2\x86\x93Long.toInt() 不安全。因为 long 到 int 会缩小
\n\nval l: Long\nl.toInt()\xe3\x80\x80\xe2\x86\x90not safety! when out of int range\nRun Code Online (Sandbox Code Playgroud)\n\n请将此函数添加到任意 kt 文件中。\n然后,将一个名为 toIntOrNull 的方法添加到 Long。\n如果该方法尝试将 long 转换为 int,且不适合 int 范围,则返回 null。
\n\nfun Long.toIntOrNull(): Int? {\n return if (this < Int.MIN_VALUE || this > Int.MAX_VALUE) {\n null\n } else {\n this.toInt()\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n或者
\n\nfun Long.toIntOrNull(): Int? {\n val i = this.toInt()\n return if (i.toLong() == this) i else null\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
14870 次 |
| 最近记录: |