简体   繁体   English

如何从kotlin中的函数返回值

[英]How to return value from the function in kotlin

I am trying to return the boolean value from the function. 我试图从函数返回布尔值。

fun  validateDetails(jabberId:String, passwordText: String) {

            if(jabberId.isEmpty()){
                jabber_id.requestFocus()
                jabber_id.error="Jabber id can't be null."
                 return false
            }else if(jabberId.isBlank()){
             jabber_id.requestFocus()
             jabber_id.error="Jabber id can't be blank."
              return false
            }else if (passwordText.isNotEmpty()){
                password.requestFocus();
                password.error="Password can't be null."
                 return false
            }
             else{
                 return true
            }   

    }

Error: The boolean literal does not conform to the expected type Unit. 错误:布尔文字不符合预期的类型单位。

I know unit is the default return type in kotlin. 我知道unit是kotlin中的默认返回类型。 How will i change this to boolean. 我将如何将其更改为布尔值。

Kotlin can only infer the returned type of a function when its a expression, so if your function has a body, you need to specify the returned type after the function paramameters Kotlin只能在表达式时推断出函数的返回类型,所以如果你的函数有一个体,你需要在函数参数后指定返回的类型

fun functionName(param: Type...): ReturnedType { 
    //function body
}

fun  validateDetails(jabberId:String, passwordText: String):Boolean {

            if(jabberId.isEmpty()){
                jabber_id.requestFocus()
                jabber_id.error="Jabber id can't be null."
                 return false
            }else if(jabberId.isBlank()){
             jabber_id.requestFocus()
             jabber_id.error="Jabber id can't be blank."
              return false
            }else if (passwordText.isNotEmpty()){
                password.requestFocus();
                password.error="Password can't be null."
                 return false
            }
             else{
                 return true
            }   

    }

As glee8e mentioned, this could be done using an expression. 正如glee8e所提到的,这可以使用表达式来完成。 This is how it'd be done. 这就是它的完成方式。

fun  validateDetails(jabberId:String, passwordText: String) = when {
    jabberId.isEmpty() -> {
        jabber_id.requestFocus()
        jabber_id.error="Jabber id can't be null."

        false
    }

    jabberId.isBlank() -> {
        jabber_id.requestFocus()
        jabber_id.error="Jabber id can't be blank."

        false
    }

    passwordText.isNotEmpty() -> {
        password.requestFocus();
        password.error="Password can't be null."
        false
    }

    else -> true  
}

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

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