0
val year : Int = spinYear.getSelectedItem() as Int
selDate.text = "$year / $month / $date"
val curTime = LocalDateTime.now()
val curYear : Int = curTime.year
val difYear : Int = curYear - year
ageInMins.text = difYear.toString()

The language is Kotlin, and this is a part of my code.

The value year comes from a spinner named spinYear, and I got the selected value as an integer. Ultimately I want to substitute the text ageInMins with the value difYear.

I'm trying to define my difYear by subtracting the two variables: curYear and year, but the app crashes every time.

It seems like both of the variables I'm subtracting are of type Int, so I have no idea what to do with this problem.

If someone could give me an advice it would be great :)

I searched around Google to find information about this, but there was no useful information. I also tried to put .toInt() to the values but it didn't work. I tried every single thing I can think of, but it did not work. So I am seeking help from you guys.

  • What error do you get? – marstran Dec 20 '22 at 11:44
  • Does this answer your question? [Unfortunately MyApp has stopped. How can I solve this?](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) – Ivo Dec 20 '22 at 11:53
  • I get something like this: public final operator fun minus(other: Byte): Int defined in kotlin.Int public final operator fun minus(other: Double): Double defined in kotlin.Int public final operator fun minus(other: Float): Float defined in kotlin.Int public final operator fun minus(other: Int): Int defined in kotlin.Int public final operator fun minus(other: Long): Long defined in kotlin.Int public final operator fun minus(other: Short): Int defined in kotlin.Int – gorilla Dec 20 '22 at 13:33
  • Don't do `spinYear.getSelectedItem() as Int` do `spinYear.getSelectedItem().toIntOrNull()` – Demigod Dec 20 '22 at 14:35
  • 1
    It's likely that `year` isn't an `Int` - casting to one with `as Int` doesn't *make* it one, it's just you telling the compiler "trust me, you don't know what type this is, but I do". But at runtime, it turns out you were wrong, and you're trying to call `curYear.minus(other)` with an object it can't handle. If you set a breakpoint on that `difYear` line you can debug the app, and look at those values to see what's actually going on - you'll probably be able to work it out! But are you sure your spinner adapter is using `Int`s? Are you handling the *null* values when something isn't selected? – cactustictacs Dec 20 '22 at 15:38

0 Answers0