im trying to figure out the best way to write some...
# announcements
s
im trying to figure out the best way to write some code for a library. in Elixir I used to be able to do something like:
Copy code
def is_ten(x) when x > 10, do: "Greater than ten"
def is_ten(x) when x < 10, do: "Less than ten"
I need to write a kotlin function that always takes a string, but the logic is completely different based on that string, is there a way to encapsulate logic into a function that is called based on the parameter value similar to elixir guard clauses?
n
I think you want something more than
fun is_ten(x: String) = if (x == "10")  do_ten(x) else do_other(x)
but I still don't get what it is you are looking for.
s
I want 3 functions with the same signature: fun a(param: String) { // do stuff if param == "TEST" } fun a(param: String) { // do stuff if param == "Debug" } fun a(param: String) { // do stuff in param == "Mock" } that are called based on the parameter value instead of its type like the elixir guard clauses I linked, I am developing a library and I want there to be one call to do multiple things so the users of the library only see 1 call, but I handle other processes in the background for them based on the value of param right now I am handling it like:
Copy code
fun runDebug(type: String) : Unit {
  if (type == "Test") {
     doA()
  } else if (type == "Debug") {
     doB()
  } else {
     doC()
  }
}
That feels really hacky, so I was wondering if something like guard clauses exist in kotlin
something like:
Copy code
fun runDebug(when type == "Test") {

}

fun runDebug(when type == "Debug") {

}
j
Copy code
fun runDebug(type: String) {
  fun test() {
    // test code
  }
  fun debug() {
    // debug code
  }
  fun mock() {
    // mock code
  }
  switch (type) {
    "test" -> test()
    "debug" -> debug()
    "mock" -> mock()
    else -> error("Unknown $type")
  }
}
maybe like this?
frankly not much different than
Copy code
fun runDebug(type: String) {
  switch (type) {
    "test" -> {
      // test code
    }
    // etc.
  }
}
though
use expression body to make it visually better:
Copy code
fun runDebug(type: String) = switch (type) {
  "test" -> {
    // test code...
  }
  // etc.
}
s
@jw It is different in this case, because the logic in each is complex. I was hoping that it wouldn't come to that, but that's what I had concluded, as well, thanks for the confirmation.