0

Below is my extension:

fun String?.toDoubleOrDefault(): Double = this?.toDoubleOrNull() ?: 0.0

when I try to apply it like this:

var a:String? = "1000"
var b:String? = "2000"
var c = a?.toDoubleOrDefault()*b?.toDoubleOrDefault()

I get this error: Type mismatch.

Required:Double

Found:Double?

Could anyone please explain what I am Doing wrong?

2
  • 1
    Do a.toDoubleOrDefault()*b.toDoubleOrDefault(). No need for null check since you already do so in the method. This is also the reason why you're getting Double? as a return value from that call. Commented Aug 8, 2020 at 9:41
  • 2
    as a side note the extension function would be more flexible as : fun String?.toDoubleOrDefault(defaultVal : Double = 0.0): Double = this?.toDoubleOrNull() ?: defaultVal Commented Aug 8, 2020 at 9:52

1 Answer 1

1

Please try below code:

    var a:String? = "1000"
    var b:String? = "2000"
    var c  = a.toDoubleOrDefault()*b.toDoubleOrDefault()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.