kamilmaestro
kamilmaestro

Reputation: 23

How to deal with type mismatch- String and String?

I'm getting a type mismatch when I want to perform an assignment. The required value is String but I have got String?. My question is: how should I deal with it, via toString method or rather by adding non-null asserted(!!) call. I'm wondering which of them is better for safety or maybe performance. The question is rather about best practices for a language.

Upvotes: 0

Views: 1788

Answers (4)

CrazyFrog007
CrazyFrog007

Reputation: 364

Try to avoid using !! operator. It should be used when you are a hundred percent sure that there's no null. It always better to use Elvis operator (default value expression which is evaluated and assigned if the expression from the left-hand side is null)

val s1: String? = null
val s2: String = s1 ?: "default value if s1 is null"

Upvotes: 0

Marcelus Trojahn
Marcelus Trojahn

Reputation: 709

I like the takeIf approach:

val someString = nullableString.takeIf { it != null } ?: ""

someString will take nullableString value unless it's null. If it's null, then it will be set to "".

I like this approach specially on Service level so the person using my service won't need treat null values ever. Obviously the logic between the {} can be far more complex than this example.

Upvotes: -1

shb
shb

Reputation: 6277

There are plenty of ways. It depends on the requirements

var str1: String? = null

//....

str1.notNull{ //no default value
    // your code
    str2 = it

}

or if you want to provide a value in case str1 is null

str2 = str1?:"default_value"

Upvotes: 0

Akash Dubey
Akash Dubey

Reputation: 1538

you can do like this

val someString : String = someOtherNullableString ?: ""

it will take the value of someOtherNullbleString if it is not null if it is null then it will take ""

Upvotes: 2

Related Questions