Loading...

sumByDouble required Double found Double?

Answer #1 100 %

try the following :

materialList.sumByDouble { elem -> elem.let { it.getPrice()?.toDouble() ?: 0.0 * it.getQuantity()?.toDouble() ?: 0.0 }

What the code above does, is assign a default value of 0.0 if either of those are evaluated to be null (Well, it assigns 0.0 to the value evaluated to be null, to be exact)

The reason for this is because your it.getPrice()? could be null, as well as your it.getQuantity()?, so what this does is essentially the same as this (entirely pseudocode)

if(it.getQuantity() == null){
 use 0.0 to perform this calculation
} else {
 use it.getQuantity()
 }

What Type mismatch. Required: Double, Found: Double? this is saying, is that the method expects a non-null double value and you are providing potentially null values


on a side-note:

I've already removed the optional with the elem.let statement, no?

doing this:

{ elem -> elem.let { stillPotentiallyNull ->

is simply a way to insure that you get an instance of elem which can not be changed by threads, however, if you did this:

{ elem -> elem?.let { definitelyNotNull ->

Then you get an instance of elem which is both safe from threads and can not be null, but this does not mean that the objects inside elem are also not null


as pointed out by @AjahnCharles, this answer is simply to explain why you're having this problem and potentially how to solve it using default values, however, you should consider how to filter out your list into non-null objects as another solution as well.

One potential solution, although it is dangerous, is to use the following :

it.getPrice()!!.toDouble() * it.getQuantity()!!.toDouble()

This is saying that you are 100% sure that these values are not null, and if they are null, this will throw a null-pointer exception.

Extra documentation you might find useful : https://kotlinlang.org/docs/reference/null-safety.html

You’ll also like:


© 2023 CodeForDev.com -