August 2018
Beginner
178 pages
4h 56m
English
Up to now, we could have substituted the generic parameter with any type. Sometimes, you may want to restrict the generic types and this can be done with generic constraints. Constraints are specified in angle brackets, with a colon, and the type that is the limit after the generic parameter. Here’s how you can limit the generic type to the Number type:
interface Countable<T: Number> { fun count(): T}
This is known as the upper bound constraint, and the compiler will allow you to substitute the generic type with the Number type and all of its subtypes. Since the Int type is a subtype of the Number type, the compiler allows this:
class IntCountable: Countable<Int> { override fun count(): Int { return 0 }}
But, the string ...
Read now
Unlock full access