Command structure for interactive console program

I’m trying to build an interactive console program. Is this the normal way of implementing a command processor in scala?

abstract class Command extends (() => Unit)

class Greet(val greeting: String) extends Command {
     def apply = println(greeting)
}

object Exit extends Command {
    def apply = System.exit(0)
}

If you have a method running on an infinite loop, would it take a cmd: Command and you would call cmd.apply() or cmd()? This seems to do the trick but there may be a better way.

Also when you do :t myCommand in the REPL you get .e.g :t Exit = Exit.type. Is there a way of getting (() => Unit)?

And would your list of available commands go into an Enumeration type, say Commands?

1 Like

I recommend looking at https://github.com/bkirwi/decline which provides a really nice structure for writing command-line programs.

3 Likes

It depends on what exactly you’re trying to accomplish.

Sounds straightforward, yes.

It is () => Unit, it’s just that the REPL reports the most specific type. You could switch to encoding via raw functions, though.

def greet(greeting: String) = () => println(greeting)
val exit = () => System.exit(0)

It depends on whether you want to keep your command set open for extension. But even if you want to limit it to a hardwired set, I’d probably rather go for a Scala sealed trait or a Java enum than a Scala Enumeration.

1 Like