Reputation: 1211
I know that it is possible to write a static generic method in Java.
I tried to implement my own solution in Kotlin but I failed.
class Wrapper<T>
{
companion object <T> // error: Type parameters are not allowed for objects.
{
private var value: T? = null
// implement some methods
}
}
Is there any way how to implement a static generic method in Kotlin?
Upvotes: 2
Views: 3813
Reputation: 48399
Generic type parameters of the class are not allowed inside the companion objects. The reason for this is that a single companion object
is shared across all the instances of that class. This is true also for the different parameterized types of the same class. So, for example, the companion object
is the same for whether it is a Wrapper<String>
or a Wrapper<Int>
. In other words, the T
of the enclosing class cannot take different forms String
or Int
inside the companion object
.
The type parameters can only be used with the member functions and member properties of the class. The value
property in your example is not the member of the Wrapper
class, it is a member of the companion object
.
This is the same thing as saying:
class Wrapper<T> {
class SomeOtherClass<T> {
private var value: T? = null
// implement some methods
}
}
The difference is just a single object vs multiple objects of SomeOtherClass
. The T
s are independent for Wrapper
and SomeOtherClass
.
That's it! Hope that points you in the right direction for the actual problem you are trying to solve.
Upvotes: 1
Reputation: 1418
companion object
is not method. It's, in fact, an object
that is companion to the Wrapper
class, therefore it cannot be aware of the generic type of parent class.
Same thing applies to Java:
public class Wrapper<T> {
public static T value; //ERROR
}
Within this companion object
you can declare methods and fields that will be static
in java world.
class Wrapper<T>
{
companion object
{
fun <T> genericMethod(){
}
}
}
But keep in mind that type of Wrapper<T>
is not connected with type T
in fun <T> genericMethod()
.
Upvotes: 7
Reputation: 6373
For Kotlin, there's no difference between static (top-level, companion) and instance functions/methods. So, the same generic function/method
fun <T> something() {
// TODO
}
is valid both within a class body, on top-level, and in companion or object declaration.
Upvotes: 2
Reputation: 2852
You just need to specify the generic type parameter of the function. It doesn't matter where the function is, be it a class, a file, a companion object, etc.
Example with companion object:
companion object {
fun <T> generic(t: T) {
// do something generic
}
}
Upvotes: 0