简体   繁体   English

以通用对象为参数的函数

[英]Function with Generic object as parameter

How to create method that takes generic object as parameter?如何创建以通用对象为参数的方法? Like object of class Apple or Cycle .像类AppleCycle对象。 I don't want to downcast it from Any .我不想从Any贬低它。

fun putObject(y: <T> /*and even only "T"*/) {
}

According to the documentation :根据文档

Not only classes can have type parameters.不仅类可以有类型参数。 Functions can, too.函数也可以。 Type parameters are placed before the name of the function:类型参数放在函数名之前:

 fun <T> singletonList(item: T): List<T> { // ... }

You have to declare that T is a type parameter.你必须声明T是一个类型参数。 You have to do it before the name of the function (like you would in Java).您必须在函数名称之前执行此操作(就像在 Java 中一样)。 Rewriting your code as follows works:重写您的代码如下有效:

fun <T> putObject(y: T) {
    // ...
}

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

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