https://kotlinlang.org logo
#codereview
Title
# codereview
d

Dave Leeds

01/09/2018, 6:50 PM
@chi It’s a bit of a different approach, but something like this might work well:
Copy code
private enum class NestingCharacters(val open: String, val close: String) {
    BRACE("{", "}"),
    PAREN("(", ")"),
    BRACKET("[", "]");

    fun apply(char: String, stack: Stack<String>) {
        when (char) {
            open  -> stack.push(char)
            close -> {
                val top = stack.peek()
                if (stack.isStackEmpty()) throw SyntaxErrorTwoException(char)
                if (top == open) stack.pop() else throw SyntaxErrorThreeException(top, char)
            }
        }
    }
}

fun linter2(line: String): Boolean {
    with(Stack<String>()) {
        line.split("").forEach { char ->
            NestingCharacters.values().forEach { it.apply(char, this) }
        }
        
        if (isNotEmpty()) throw SyntaxErrorOneException(peek())
    }
    return true
}
2
c

chi

01/09/2018, 9:08 PM
Thanks! Would look at it
How did you define
BRACE
,
PAREN
and
BRACKET
?
d

Dave Leeds

01/09/2018, 10:01 PM
They’re just part of that
enum
, so that’s the full definition in the code listing above.
So for example, doing
BRACE("{", "}")
is invoking the constructor on
NestingCharacters
, setting
open
to
{
and
close
to
}
.
1
2 Views