Generics

We've already seen generics in previous chapters, and in this section, we'll learn how they work, how they are implemented, and what the differences are from generics in Java.

Simply put, generics are types with parameters. Take a look at the List interface, for example; without generics, you could add objects of any type to it. But, since the list interface is generic, you have to specify a generic type for when you are creating an instance of it. You can create a list of strings, a list of integers, and so on. This then makes the list type-safe; you cannot add an integer to a list of strings.

The generic type is specified in angle brackets, so a list of strings type is declared like this:

List<String> 

Creating an instance of a generic type is the same as creating normal types; you call a generic class constructor and specify the generic type argument:

val strings: List<String> = ArrayList<String>()

Type inference works with generics also, so supplying the generic argument of string in the ArrayList class constructor is redundant. When a variable has declared a generic type, then you can omit it from the constructor:

val strings: List<String> = ArrayList()

Type inference also works on variables; if there is enough information from the variable declaration, you can omit the type:

val strings = ArrayList<String>()
..................Content has been hidden....................

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