![]() ![]() We’ll put aside nullable types for a moment, and look at just the hierarchy of non-nullable types. Just like classes, types exist in a hierarchy. Some of these would be List, List?, List, List?, List>, List, List… Just to mention a few. ![]() In fact, this unbounded T type parameter introduces infinitely many types. These are separate and very different types, as the compiler forces us to explicitly handle the possible nullability of a Hello? in the form of null checks, while letting us use a Hello relatively freely in comparison, since it knows it’s safe to do so.Ĭreating a class with a type parameter introduces yet more types: class List Let’s take just the case of a boring, empty class: class Helloīy defining this class, we’ve already created the Hello and Hello? types. In fact, in all of these cases, we’re creating multiple new types with these declarations. We are creating a new type every time we declare a class, interface, object, or typealias (going forward, we’ll stick to just classes for simplicity). It’s important to note that types are not equivalent to classes. ![]() This eliminates a whole class of possible runtime errors that might occur in dynamically typed languages. What properties and methods can be called on it, where it can be passed as a parameter, where it can be assigned.Įvery variable, property, parameter, and expression has a type in Kotlin at compile time - this static typing is what guarantees that, for example, no calls are made to non-existent functions. What’s a type?įirst things first, what exactly is a type? Types are what let us and the compiler define expectations we have for any given object. Let me invite you on a tour of Kotlin’s type system, exploring how some of the language constructs we take for granted in our everyday use - as they just “make sense” - work.ĭisclaimer: Some illustrations presented here to explain the type hierarchy are inspired by the ones in this blog post by Nat Pryce from 2 years ago, as well as in KotlinConf 2017 talks by both Svetlana Ivanova and Christina Lee. This post was originally posted on, which is now unavailable.
0 Comments
Leave a Reply. |