Tanguy Epifanic
Tanguy Epifanic

Reputation: 225

How to initialize a property with an unknown type in Kotlin?

I'm a beginner in Kotlin and I'm actually doing an Androïd application in Kotlin. I have to initalize some properties whose values are unknown (it isn't but it's hard to define from now) so I'd like to make as in TypeScript, for example: public startDate: any; which means that the type of startDate could be anything (it isn't secured but it helps to get the value anyway, not regarding what happens).

Is there a way to do it in Kotlin? I tried the '?' or the * as in the List<*> or parameters but it doesn't work that way.

Thanks for reading!

Upvotes: 5

Views: 4159

Answers (3)

Noah Studach
Noah Studach

Reputation: 445

As mentioned you should use the Any type. Depending on your need use val or var (val vs var)

    var myVal : Any

If your variable can also be null us ?

    var myVar: Any?
    val myVal : Any?

You also need to either make you variable abstract or declare that it will be initialized later. lateinit is only valid for var, while abstract is applicable for val's and var's

    lateinit var myVar: Any
    abstract val myVal : Any

Dont forget to check if lateinit var are initializerd:

if (::myVar.isInitialized) {
    //use myVar
}

More about the Any type

Null Safety

Upvotes: 0

TheOperator
TheOperator

Reputation: 6466

Use the type Any if the property can contain any object (but not null, which implies it must be initialized immediately).

Use the type Any? if the property can contain any object or null. This is equivalent to Java's Object type.


From a design point of view, it's of course nicer if you know the actual type and can make use of Kotlin's strong type system. If you or your team are defining the types, you might constrain them to implement a certain interface, so you don't assign arbitrary values to it. Later, when refactoring the application, you can remove this interface and will receive compile errors for all the occurrences, forcing you to properly fix it.

Upvotes: 1

Dmitriy Pavlukhin
Dmitriy Pavlukhin

Reputation: 419

Like Object as base class in java, you may use Any in kotlin.

Upvotes: 0

Related Questions