How to use scopt(

In this post, we are going to see how we can use scopt which is a scala library used to parse the command-line options.

The GitHub URL is

We may need to read and parse the command line arguments. So this simple command line parser used to reduce our burden.

Let’s see how we can use this with a simple example.

Assume that you want to read two parameters from the command line, they are input and output directory respectively. You want to throw an error if those parameters are not available.

package com

object ScalaApp extends App {

    case class Arguments(inputDir: String = "",
                         outputDir: String = "")

    val parser = new scopt.OptionParser[Arguments]("Parsing application") {

        opt[String]('i', "inputDir").
            required().valueName("").action((value, arguments) => arguments.copy(inputDir = value))

        opt[String]('o', "outputDir").
            required().valueName("").action((value, arguments) => arguments.copy(outputDir = value))


    def run(arguments: Arguments): Unit = {
        println("Input Dir:" + arguments.inputDir)
        println("Output Dir:" + arguments.outputDir)

    parser.parse(args, Arguments()) match {
        case Some(arguments) => run(arguments)
        case None =>


In the above example, I have created a case class Arguments has two fields, input and output directory and I parse the input arguments, if the value is available, then I assign the value to the corresponding field in the case class.

When I run the program with the below command line arguments, then the output will look below,

-i /home/bala/input -o /home/bala/output

com.ScalaApp -i /home/bala/input -o /home/bala/output
Input Dir:/home/bala/input
Output Dir:/home/bala/output

When i run the program without any command line arguments, then it will show the below error as i specified those arguments as required arguments.


Error: Missing option --inputDir
Error: Missing option --outputDir
Usage: test [options]

  -i, --inputDir    
  -o, --outputDir   

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s