It's possible to do this? `fun<T: Any> testi...
# announcements
r
It's possible to do this?
fun<T: Any> testing( id: UUID, name: String) : T {
return T
}
If no, how do I return a T ?
🚫 3
c
first of all, to work with
T
it needs to be reified, second of all, its type would be
KClass<T>
, not
<T>
. That said, maybe you mean something else, what do you want to achieve?
r
My function always returns an object. Command. Event ... the list is long. But the parameters are always the same:
fun process (id: UUID, commandStatus: CommandStatusEnum, message: Any): Command (or other class) {
return Command (id, status, message)
}
I don't want to create a function for each type of return, so I wanted to use Generics
d
typealias Process<T> = (id: UUID, name: String) -> T
Wait why wouldn't you create a function for each type of return?
you should definititely do that, and then maybe you can add another function that pulls them all together
👍 1
c
Agreed with Dico, unless all the possible returns share an interface, you should not just rely on the fact that they have same parameter list in constructor, even though what you want to do is technically possible.
☝🏻 2
That said, there is a Kotlin way to do a similar thing using higher order functions. E.g.
Copy code
enum class CommandStatusEnum {
	A, B, C
}

class Event(id: UUID, commandStatus: CommandStatusEnum, message: Any)
class Command(id: UUID, commandStatus: CommandStatusEnum, message: Any)

fun <T : Any> process(
	id: UUID,
	commandStatus: CommandStatusEnum,
	message: Any,
	creator: (id: UUID, commandStatus: CommandStatusEnum, message: Any) -> T
)T {
	/* process stuff */
	return creator(id, commandStatus, message)
}

// usage
process(UUID.randomUUID(), A, "", ::Event)
What makes this possible is that you know the type of object you want to receive, and resulting function is type-safe, whereas
fun <T> process(id: UUID, commandStatus: CommandStatusEnum, message: Any): T
would require inlining, reification and use of reflection and would not be type-safe or refactoring friendly at all.