https://kotlinlang.org logo
Title
t

Tony Blundell

08/12/2019, 10:03 AM
fun doSomething() {
  // return instance of whatever is between the angle brackets below
}

val x = <MyType>doSomething()
val y = <MyOtherType>doSomething()
How should the signature of doSomething look?
Thanks, but then I get a warning, Type mismatch, required Unit, found T… do I need to specify return type at the end somehow?
a

Ash

08/12/2019, 10:07 AM
You should return T as well
Return type of the function should be T
t

Tony Blundell

08/12/2019, 10:09 AM
Ah cool, and how would I reference the type inside the function? Eg, I want to pass it to something like
return mapper.readValue<T>(xmlOut)
b

Big Chungus

08/12/2019, 10:09 AM
inline fun <reified T> doSomething(): T {
  return T::class.constructors.toList()[0].call()
}
👍 1
🧠 1
t

Tony Blundell

08/12/2019, 10:12 AM
👍 it worked - thank you!
k

karelpeeters

08/12/2019, 10:41 AM
This is a pretty strange thing to do, if you know the type you can just call the constructor yourself no?
b

Big Chungus

08/12/2019, 10:42 AM
Exactly, not sure what op is trying to achieve
t

Tony Blundell

08/12/2019, 10:42 AM
Well, I’m actually passing the type on to a Jackson XML mapper - I’m just telling the function what type I want the XML mapped back to.
Looks like this in the end:
private suspend inline fun <reified T> makeXmlRequest(req: Any): T {
        val xmlIn = mapper.writeValueAsString(req)
        val xmlOut = <http://client.post|client.post><String>(url) { body = xmlIn }
        return mapper.readValue(xmlOut)
    }
👍 1
k

karelpeeters

08/12/2019, 10:46 AM
Oh my bad, I thought you meant to actually call the constructor.
t

Tony Blundell

08/12/2019, 10:46 AM
👍 no, I probably could have worded it better 🙂