Paulo Buchsbaum
Paulo Buchsbaum

Reputation: 2649

KOTLIN: How to assign a default valor for a generic type parameter in a function?

My problem is simple (Maybe not the solution...)

I've defined a generic pointer:

data class pTp<T>(   // It's a generic wrap class for scalar type T
  var v:T
)

I what that this generic pointer works with many structured data:

data class Agenda (
 var name: String="",
 var address: String=""
)

If I want to use that type in a function, no problem:

fun example(...., pAg: pTp<Agenda>, .....){

}

The below function call works smoothly

var agen: pTp<Agenda> = pTp(Agenda())
... example(...,pAg=agen,...)

or

... example(...,pAg=pTp(Agenda()),...)

However, the below code for having a default value for this parameter it doesn't work...

fun example(...., pAg: pTp<Agenda>=pTp<Agenda>(Agenda()), .....){

}

Neither

fun example(...., pAg: pTp<Agenda>=pTp>(Agenda()), .....){

}

However, it's the same code that I've used in the initialization of the caller!

So, I don't know how to do this initialization.

UPDATE: The right answer is below. Just use a space before =. Crazy!

Upvotes: 0

Views: 409

Answers (1)

Sergio
Sergio

Reputation: 30595

Please use next syntax and it will work:

fun example(pAg: pTp<Agenda> = pTp(Agenda())) {
    // ...
}

Upvotes: 1

Related Questions