简体   繁体   English

KOTLIN:如何为 function 中的泛型类型参数分配默认值?

[英]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:如果我想在 function 中使用该类型,没问题:

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

}

The below function call works smoothly下面的function通话正常

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!疯狂的!

Please use next syntax and it will work:请使用下一个语法,它将起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM