Declaring generic types

You can declare a generic class or interface with angle brackets after the type name. In the angle brackets, you specify the name of your generic type parameter. Usually, generic types are called T or E.

Let's see how the generic Array class is declared in the Kotlin Standard Library:

public class Array<T> {

public inline constructor(size: Int, init: (Int) -> T)

public operator fun get(index: Int): T

public operator fun set(index: Int, value: T): Unit

public val size: Int

public operator fun iterator(): Iterator<T>
}

Notice, how, in the generic type declaration, there is no information about the actual generic type argument. We only reserved a place for it and gave it a name, T. The actual generic type argument will be given at compile time.

You can see how, in the body of the class, we have access to the generic T type. For example, the get function returns the generic type. When you create an instance of, let's say, an array of strings, then this get function return type will be a string type.

Declaring a generic interface is done in the same way as with generic classes, with angle brackets after the type name:

interface Generic<T> {
fun foo(t: T)
}

When implementing this interface, you have to specify a generic type. This class uses the Int type as the generic type:

class IntGeneric: Generic<Int> {
override fun foo(t: Int) {

}
}

You can see how the foo method's parameter also changes to the Int type.

We can also let the callers of our class decide upon the generic type. We do this by declaring the class itself to be generic:

class GenericType<T>: Generic<T> {
override fun foo(t: T) {

}
}

Notice how the foo method's parameter is again now of the generic T type.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.44.236