problems perform cast kotlin on "android"

0

I'm trying to do "castings" in android kotlin mendiante, as I did a couple of months ago ..... but I always get an error, do you know if it's a bug?

So far I was casting this guy and they worked for me

var variable1:Int=12.11 as Int
var variable1=12.11 as Int

but now I make this type of cast and I get an error, I do not know if they have changed something or it is a bug, I have tried to execute it in API 26, 27, 28, and it keeps giving error

    
asked by thimp 10.06.2018 в 18:26
source

2 answers

2
  

You can not make a cast directly a class Double to a class Int . Also, Double e Int are immutable objects, so you can not modify them in any way.

Primarily, if the cast can be done, but in this case classes are being handled, so if they do not have any inheritance relationship, it is impossible to make the cast because it will cause an exception.

In your example you have the following:

var variable1=12.11 as Int

The most you can do that way is to avoid the exception and return null with as? instead of as in the conversion.

According to the Kotlin official documentation the values marked as Double you can get the whole of it with the function toInt() so in your case you can do the following:

var variable1:Int = 12.11.toInt()

All types or numerical representation classes support the following methods:

toByte(): Byte
toShort(): Short
toInt(): Int
toLong(): Long
toFloat(): Float
toDouble(): Double
toChar(): Char

You can see more examples in the Documentation on the basic types .

    
answered by 10.06.2018 в 19:37
1

Hello here my contribution forget about the cast and the findViewById in Kotlin you just need to add the following import :

import kotlinx.android.synthetic.main.activity nombre del paquete.*

With that we can call directly buttons, bars, etc ... and use their methods through their id without having to cast or have to use the findViewById

    
answered by 09.09.2018 в 19:18