Using ModelMapper in kotlin spring boot

Viewed 152

In few of my projects in spring boot I have used ModelMapper (https://www.baeldung.com/java-modelmapper). However now I am writing an app using Kotlin, and I couldn't find any solution that would be easier to use for converting objects from one class to another. Let's say that we have two classes like these:

class Test(val name: String, val size: Int)

class AnotherTest(val name: String, val size: Int, val id: String)

If these classes were written in Java, we could convert AnotherTest to Test like this:

//   some class definition with modelMapper of ModelMapper type field, methods
    
    public Test convertToTest(AnotherTest anotherTest) {
        Test testInstance = this.modelMapper.map(anotherTest, Test.class);
    }

I think using something like Test.class is illegal in Kotlin, so how should I write this function in Kotlin?

When I tried it myself by writing it the same way as in java:

fun convertToTest(another: AnotherTest): Test = this.modelMapper.map(another, Test.class)

I am getting 2 errors:

Name expected
Expecting ')'
1 Answers

Maybe it's illegal* but, until cops will find you, you can use for example

fun convertToTest(anotherTest: AnotherTest) = modelMapper.map(anotherTest, Test::class.java)

Read more here:

Also reified types may be interesting for you


* just joking it's not illegal :)

Related