Rate my bad code: ``` class Else<R> private constr...
# codereview
d
Rate my bad code:
Copy code
class Else<R> private constructor(private val value: Any?) {
    infix fun `else`(alternative: () -> R): R =
        if (value == IsNot) alternative() else value as R

    companion object {
        private object IsNot

        fun <R> `is`(value: R) = Else<R>(value)
        fun <R> `isn't`() = Else<R>(IsNot)
    }
}

fun <R> `if`(condition: Boolean, value: () -> R) = if (condition) Else.`is`(value()) else Else.`isn't`()
e
@Daniel Pitts please give an example how do you use it
d
It basically allows you to defer the
else
in an if/else.
Copy code
fun foo(helloWorld:String) = 
  `if` ("hello world" == helloWorld) { 
     handleHelloWorld()
  }


fun bar(str: String) =
   foo(str) `else` {
      println("It wasn't Hello World.")
   }
e
@Daniel Pitts I still don’t follow why you could need that. Do you have a real world example?
d
Copy code
private fun <R> withActiveWindow(active: (GLFWwindow) -> R): Else<R> {
        main.checkThread()
        return `if`(glfwWindow != NO_WINDOW) { active(glfwWindow) }
    }

     var title: String = ""
        set(value) {
            withActiveWindow { 
              glfwSetWindowTitle(it, field) 
            } `else` { field = title }
        }
It's basically an Optional with slightly different syntax.
FWIW, I ended up not going this route, for various other reasons, and I also don't think it's good code in the first place. One of those "too clever" things.
e
Yeah, I think it is hardly following KISS
👍 1
d
It's fun though. I could see using something similar in a DSL for some project, but probably wouldn't use the backtick names