RonRon Scores
RonRon Scores

Reputation: 193

How to set a property of a created object in kotlin?

I have seen many different similar questions on this site referencing this problem, but all aims at creating the property from inside of the class itself. I have been looking over the kotlin docs for a while , and can't seem to find a solution. I am trying to take in a random object and add a attribute to it.

//create this object
class random(val name : String?){

}

var obj = random("bob")
obj.newattribute :Int = 2 //cant do this in this lang

Upvotes: 2

Views: 4854

Answers (2)

Joffrey
Joffrey

Reputation: 37720

In Kotlin, you cannot (and shouldn't anyway) change the "shape" of your instances at runtime, because the type system is here to protect users and provide guarantees on the values you're manipulating.

That being said, if what you need is a key-value store, where you can put key-value pairs and access values by their key, you should use an implementation of the MutableMap interface.

For instance, HashMap is an implementation of that interface:

val myMap = HashMap<String, Int>()
myMap["newattribute"] = 2

println(myMap["newAttribute"]) // prints "2"

Note that the type of the keys and the values is well defined. A given Map can only deal with keys of the same type (here Strings), and values of the same type (here Ints). This means you cannot do myMap["stringProperty"] = "text" with the map defined in the above example.

If you really want something more general (especially for the values), you would need to use a wider type as your "values" type in the map. For instance, use MutableMap<String, Any> instead, so that the values can be of any non-null type:

val myMap = HashMap<String, Any>()
myMap["intAttr"] = 42
myMap["strAttr"] = "text"

println(myMap["intAttr"]) // prints "42"
println(myMap["strAttr"]) // prints "text"

Upvotes: 5

deHaar
deHaar

Reputation: 18568

It looks like your intention is to manipulate a class at runtime by adding a new attribute to an instance of that class.

If you read the documentation of Kotlin classes, you will stumble upon the following paragraph (the first one in the linked documentation):

Kotlin's object model is substantially different from Python's. Most importantly, classes are not dynamically modifiable at runtime! (There are some limited exceptions to this, but you generally shouldn't do it. However, it is possible to dynamically inspect classes and objects at runtime with a feature called reflection - this can be useful, but should be judiciously used.) All properties (attributes) and functions that might ever be needed on a class must be declared either directly in the class body or as extension functions, so you should think carefully through your class design.

This simply means it is not possible in Kotlin and it states that you shouldn't even make heavy use of runtime inspections, which are possible.

Upvotes: 4

Related Questions