Home > Mobile >  how to fix required Long found Long?
how to fix required Long found Long?

Time:11-04

i am trying to add two number whose type is Long

@Entity
data class Monitor(
        @PrimaryKey
        @NonNls
        var parentUsageDuration: Long? = 0L,
        var childUsageDuration: Long ?= 0L
)

there is two number

var parentTime = homeViewModel.getMonitorAllDataItem()?.parentUsageDuration
var childTime =  homeViewModel.getMonitorAllDataItem()?.childUsageDuration

when i try to add this two number

 var totalTime =  parentTime  childTime

I am getting error

required Long found Long ? 

unable to add this two number please help me to fix this issue.

CodePudding user response:

Problem is that parentTime and childTime numbers are not just numbers. They are numbers or nulls - notice ? char in Long?. It is not possible to perform math operations on nulls, so we need to decide what do to in the case of nulls. Most common solutions are:

Set totalTime to null if at least one of numbers is null:

var totalTime = if (parentTime == null || childTime == null) null else parentTime   childTime

Replace nulls with some defaults, e.g. 0:

var totalTime = (parentTime ?: 0)   (childTime ?: 0)

Or, if we are sure that in fact these values can't be null:

var totalTime = parentTime!!   childTime!!

If this is the case then you should also consider changing the type of parentUsageDuration and childUsageDuration to not-nullable Long, but it really depends on your specific case.

CodePudding user response:

parentTime and childTime have type Long? while totalTime has type Long. You can fix it via changing type. Like

var parentTime:Long = homeViewModel.getMonitorAllDataItem()?.parentUsageDuration!!
  • Related