我正在try 使用Kotlin 语言制作一个简单的Android应用程序. 我有一个EditText,我以字符串形式获取它的值,但我想将该值转换为整数. 我怎样才能把这个字符串转换成Kotlin language的整数呢?

推荐答案

您可以使用.toInt():

val myNumber: Int = "25".toInt()

Note that it throws a NumberFormatException if the content of the String is not a valid integer.

If you don't like this behavior, you can use .toIntOrNull() instead (since Kotlin 1.1):

val myNumOrNull: Int? = "25".toIntOrNull()

Kotlin相关问答推荐

调用即发即忘方法--哪个作用域?

带有Spring Boot和Kotline的可嵌入实体

在Kotlin中将String转换为T

Kotlin扩展函数未调用Hibernate/JPA中的重写函数

Kotlin - 协程未按预期执行

为什么这个 Kotlin 代码不起作用? (如果 str[index] 在列表中,则打印)

测试协程和线程之间的差异,我在kotlin中使用线程时无法得到OOM错误

kotlin 如何决定 lambda 中的参数名称?

JavaFX - 你如何在 Kotlin 中使用 MapValueFactory?

jetpack compose 将参数传递给 viewModel

Kotlin - mutableMapOf() 会保留我输入的顺序

Kotlin:如何在活页夹中返回正在运行的服务实例?

main函数和常规函数有什么区别?

Kotlin not nullable值可以为null吗?

编译错误:-Xcoroutines has no effect: coroutines are enabled anyway in 1.3 and beyond

Kotlin lambda 语法混淆

Kotlin中保留的关键字是什么?

具有泛型param的Kotlin抽象类和使用类型param的方法

如何使用mockk库模拟android上下文

如何在 Kotlin 中定义新的运算符?