i'm trying to parse an environment variable with a...
# getting-started
r
i'm trying to parse an environment variable with a sensible default, and since this is a learning experiment as much as anything else, i'd like to use pattern matching. is this is a sensible approach, or should i stick to assigning the value of a
try/catch
?
Copy code
val port: Int = when (val p = System.getenv().getOrDefault("PORT","8080").toInt()) {
      is Int -> p
      else -> 8080
    }
d
Except that this won't work.
toInt
will throw if it can't parse it so you will just get an uncaught exception. You can only catch exceptions using
try-catch
. If you want to use "pattern matching", you have to use
toIntOrNull
, which will return null in case of an unparseable value:
val port = System.getenv().getOrDefault("PORT", "8080").toIntOrNull() ?: 8080
r
ahaaa, thank you very much. i was wondering if the
else
case would catch an exception, and i guess it doesn't!
is there a way to remove the
val p =
part of that and still use the value?
declaring an intermediate value seems redundant
d
No, that's what the
val p =
syntax is for
but using
when
here is way overkill anyways.
r
is there a better or more concise approach? i'm all ears 🙂
or, er, all eyes
d
Read above 🙂
I posted an example
r
oh so you did, my bad
thank you very much dude, you rock 😄
s
there no point parsing 8080 string to int unncessarily
val port = System.getenv("PORT")?.toIntOrNull() ?: 8080
👆 1
âž• 4