Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple casting in Kotlin/Java

Tags:

casting

kotlin

I have an object User defined as below

class User(){
    var id: Int? = null
    var name: String? = null}

For certain reasons, I have to create new object User of same parameters and I have to copy data from old to new type.

class UserNew(){
    var id: Int? = null
    var name: String? = null}

I was looking for easiest way to convert from old type to a new one. I want to do simply

var user = User()
var userNew = user as UserNew

But obviously, I am getting This cast can never succeed. Creating a new UserNew object and set every parameter is not feasible if I have a User object with lots of parameters. Any suggestions?

like image 887
musooff Avatar asked Dec 06 '25 04:12

musooff


1 Answers

as is kotlin's cast operator. But User is not a UserNew. Therefore the cast fails.

Use an extension function to convert between the types:

fun User.toUserNew(): UserNew {
    val userNew = UserNew()
    userNew.id = id
    userNew.name = name
    return userNew
}

And use it like so

fun usingScenario(user: User) {
    val userNew = user.toUserNew()
like image 92
Frank Neblung Avatar answered Dec 10 '25 20:12

Frank Neblung