Search code examples
androidkotlinandroid-intentargumentstoast

Android(Kotlin) Toast using Elvis Operator to use a Default String value when value from intent/arguments is Null


I have this kind of implementation

Toast.makeText(activity,arguments?.get("message") as String, Toast.LENGTH_SHORT).show()

So, the thing is I want to make the use of Elvis Operator(?:) here, so as to use some default String, when the value to show inside toast is Null. I could not implement it properly. So, How do I implement it in the same line of code ??. Also, what will be the better way to do it ?? Thanks.


Solution

  • Simply put elvis operator after the nullable get call:

    Toast.makeText(activity, arguments?.get("message") ?: "Default value", Toast.LENGTH_SHORT).show()
    

    Here's some observations:

    • null ?: "default" evaluates to default
    • "valid str" ?: "default" evaluates to valid str