1

I have written the below code while learning Kotlin language.

class UserAdmin<T>(credit: T) {
    init {
        println("Class with generics: " + credit)
    }
}

class UserAdminAny(credit: Any) {
    init {
        println("Any class: $credit")
    }
}

fun main(args: Array<String>) {

    var user = UserAdmin<String>("String")
    var user2 = UserAdmin<Int>(1)

    var userAny = UserAdminAny(1)
    var userAny2 = UserAdminAny("String")
}

The output of the program is:

Class with generics: String Class with generics: 1 Any class: 1 Any class: String

I would like to know what are the differences between "Any" keyword and generics in Kotlin and when and where to use them. Both here, gives same responses.

Thanks in advance.

  • 2
    It's mostly the same as for java (though `Any` works a bit different than `Object`), see e.g.: https://stackoverflow.com/questions/5207115/java-generics-t-vs-object – UnholySheep Mar 08 '18 at 08:00

1 Answers1

2

It's mostly about compile-time type safety from a client's point of view. Take this one:

class UserAdmin<T>(val credit: T)
class UserAdminAny(val credit: Any)

val user = UserAdmin("String")
println(user.credit.length)
val userAny2 = UserAdminAny("String")
println(userAny2.credit.length) //does not compile, you'd need to cast Any to String before!

As a client, you want the property to be String rather than having to cast that Any type, which could basically be anything and probably can fail at runtime, whereas generics give you the type safety at compile time already.

The main advantages of generics:

  • Elimination of Type Casting
  • Stronger type checking at compile time
  • Enabling programmers to implement generic algorithms
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196