简体   繁体   English

kotlin / java-是否有类似TryParse()的东西?

[英]kotlin / java - Is there something like TryParse()?

I need to convert 3 editText to Double and do an automatic calculation. 我需要将3 editText转换为Double并进行自动计算。 The problem is: in Java, using Double.parseDouble() throw an exception if editText string is null so I have to use a try catch. 问题是:在Java中,如果editText字符串为null,则使用Double.parseDouble()引发异常,因此我必须使用try catch。 In Kotlin, using toDoubleOrNull I have to check with an "if" if is null or not. 在Kotlin中,使用toDoubleOrNull必须检查“ if”是否为null。

Now, with 2 editText i have to do val a = firstDobule + secondDouble and then val b = a + 2 But using aboved methods I can't separate the calculation: it need to convert all 3 editText in the same time and I want to convert a singular editText at time. 现在,对于2个editText,我必须执行val a = firstDobule + secondDouble ,然后val b = a + 2但是,使用上述方法,我无法分开计算:它需要同时转换所有3个editText,我想一次转换单数editText。

to make you understand better, this is the code in C#: 为了使您更好地理解,这是C#中的代码:

 Double.TryParse(firstEditText.Text, out Double firstDouble);
 Double.TryParse(secondEditText.Text, out Double secondDOuble);

Double a = firstDouble + secondDOuble;
Double b = a + 2;

In C#, using TryParse it doesn't throw any exception and doesn't need to check manually if is null or not. 在C#中,使用TryParse不会引发任何异常,也不需要手动检查是否为null。 I want to do this, but in Kotlin or Java 我想这样做,但是在Kotlin或Java中

You can write an extension function for EditText that will return its text value as a double. 您可以为EditText编写一个扩展函数,该函数将其文本值作为双EditText值返回。

fun EditText.doubleValue() = text.toString().toDoubleOrNull() ?: 0.0

This assumes you want to get 0 in case of unparsable input. 假设您要在输入不可解析的情况下获得0。 Then you can read off values easily: 然后,您可以轻松读取值:

val a = firstEditText.doubleValue() + secondEditText.doubleValue()
val b = a + 2

I think @Pawel is on the right track, however, I'd define an extension property instead of an extension function, as it seems to be more appropriate semantically: 我认为@Pawel在正确的轨道上,但是,我将定义一个extension属性而不是一个extension函数,因为它在语义上似乎更合适:

val EditText.doubleValue: Double
    get() = text.toString().toDoubleOrNull() ?: 0.0

The usage would then look like this: 用法如下所示:

val a = firstEditText.doubleValue + secondEditText.doubleValue
val b = a + 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM