Im on a roll tonight! Im trying to get the current...
# getting-started
s
Im on a roll tonight! Im trying to get the currentSeason(summer) 'badModifier' and 'goodModifier' values from the Summer object ( both are type Double ) . I am setting 'currentSeason' to String value "Summer". How do i use that String value of "Summer" as an object get. See the code attached. I dont want it to = "Summer", but Summer(the object)
s
Best way: turn your seasons into an enum!
Copy code
enum class Season(
  val goodModifier: Double, 
  val badModifier: Double
) {
  Summer(1.20, 0.90),
  Fall(…, …),
  Winter(…, …),
  Spring(…, …)
}
Then you just use
valueOf()
to get a season by name:
Copy code
val season = Season.valueOf("Summer").goodModifier
2
💯 1
If for some reason you can't use an enum, you could just make a map instead:
Copy code
val seasons = mapOf("Summer" to Summer, …)
s
Cheers sam. I think the enum route sounds perfect. I'm guessing these enums can have enless variables inside like any class?
s
Yes, an enum can do most of what an ordinary class can do. If you need to add a proper class body, you put a semicolon after the list of constants:
Copy code
enum class MyEnum {
  Foo, Bar;

  val greeting = "Hello, $name"
}

println(Foo.greeting) // "Hello, Foo"
👍 1
s
after usung the enum, im still struggling to use the "String" value as an object. Im thinking its not possible.
Copy code
// Seasons variables
public val currentSeason = findSeason()
public var currentGoodSeasonName = currentSelectedAbility.preferedSeason
public var currentBadSeasonName = currentSelectedAbility.nonPreferedSeason
public var currentGoodSeasonModifier = Seasons.currentSeason.goodModifier
public var currentBadSeasonModifier = currentSeason.badModifier


public enum class Seasons(goodModifier: Double, badModifier: Double, name: String) {
   Summer(1.20,0.90, "Summer"),
   Winter(1.20,0.90, "Winter"), 
   Spring(1.20,0.90, "Spring"),
   Autumn(1.20,0.90, "Autumn")
    
}
s
Don't forget the
valueOf
function to get from the String to the object
By the way, enums automatically have a `name`; you don't need to add it yourself
👀 1
👍 1
s
im clearly missing something here.. 😕
s
Just the
val
keyword in your constructor properties
s
Ohhhhhhhh. OK that works. That makes sense..I think. Still wrapping my head around it lol. If you dont set the constructor as a val, what type are they?
s
Without
val
, they're constructor parameters that will be available during initialisation, but not after. Adding the
val
keyword assigns them to properties that can be accessed later on.
s
Thank you Sam!!! Your a legend
🍻 1