Home > Software design >  What consequences does it have, if I use `Any` as a type parameter constraint in general?
What consequences does it have, if I use `Any` as a type parameter constraint in general?

Time:12-04

I can use an unconstrained type paramter:

interface State<V>

or I can use a constrained type parameter:

interface State<V: Any>

This seems to be the same, because "In Kotlin, everything is an object [...]". But this may be deceptive. What consequences does it have, if I favor the second instead of the first?

CodePudding user response:

Using Any as a type parameter constraint in Kotlin has the effect of allowing any type to be used as a type parameter. This can be very useful in some cases, as it allows you to create generic functions and classes that can accept any type, but it also has some drawbacks. For example, using Any as a type parameter constraint can lead to code that is not type-safe and can make it difficult to debug potential errors. Additionally, it can make it difficult to understand the code and can lead to unexpected behavior.

CodePudding user response:

Please be aware the default upper bound is not Any, but Any?. There is no difference if we write interface State<V> or interface State<V : Any?> - this is the same thing.

However, interface State<V : Any> is different, it constrains T to be not nullable type:

interface State<V : Any>

class StringState : State<String> // ok
class NullableStringState : State<String?> // compile error

Both above classes compile fine if we don't specify the upper bound or we set it to Any?.

  • Related