musooff
musooff

Reputation: 6882

Simple casting in Kotlin/Java

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?

Upvotes: 2

Views: 4411

Answers (6)

Zulqarnain
Zulqarnain

Reputation: 651

To achieve you can Simply use Gson and avoid boilerplate code:

var user = User(....)

val json = Gson().toJson(user)

val userNew:UserNew =Gson().fromJson(json, UserNew::class.java)

Upvotes: 2

Sasi Kumar
Sasi Kumar

Reputation: 13358

you should follow this logic for this case. note: @Frank Neblung answer i implemented

fun main(args: Array<String>) {
val user = User()
user.id = 10
user.name = "test"
var userNew = user.toUserNew()
println(userNew.id) // output is 10
println(userNew.name)// output is test
 }


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

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

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

Upvotes: 1

Gilkan Solizaris
Gilkan Solizaris

Reputation: 98

To achieve that you can use the concept of inheritance:

https://www.programiz.com/kotlin-programming/inheritance

Example:

open class Person(age: Int) {
// code for eating, talking, walking
}

class MathTeacher(age: Int): Person(age) {
// other features of math teacher
}

Upvotes: 0

Frank Neblung
Frank Neblung

Reputation: 3175

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()

Upvotes: 4

Pavel Niedoba
Pavel Niedoba

Reputation: 1577

You have two options. Either create interface and implement it in both classes. then you can use this interface in both places (User,UserNew) If this is not what you want, i would use copy constructor in UserNew taking User as parameter, You can create new

NewUser nu = new UserNew(userOld)

if you have lots of properties answer from ppressives is way to go

Upvotes: 0

ppressives
ppressives

Reputation: 51

If you don't want to write a boilerplate code, you can use some libraries that will copy values via reflection (for example http://mapstruct.org/), but it's not the best idea.

Upvotes: 2

Related Questions