Richard Desouza
Richard Desouza

Reputation: 259

Is there anyway to implement optional command line arguments in Scala?

I want to implement command lines in my program so that they can be optional but as of now the only way I can get my program to run is if I input 3 arguments when I run the program in the command line. Is there any way to have it so I only have to input a minimum of one argument and have the other 2 as optional?

Here is the start of my code:

 import scala.collection.mutable.ListBuffer
 import util.control.Breaks._
 object part3 {
   var newStartTime = 0
   var newEndTime = 0
   var csvStartTime = 0
   var csvEndTime = 0
   def main(args: Array[String]): Unit = {
     var csV = args(0)
     var daY = args(1)
     var time1 = args(2)
     var time2 = args(3)
     newEndTime = checkLengths(time1, time2)
     val bufferedSource = io.Source.fromFile(csV)
     var z = new ListBuffer[String]()
     var z2 = new ListBuffer[String]()
     var i = 0

Updated code:

val fileName = args(0)
courseCode1 = args(1)
val courseCode2: Option[String] = Try(args(2)).toOption
val courseCode3: Option[String] = Try(args(3)).toOption

val extraCourseSelection = for {
    c2 <- courseCode2
    c3 <- courseCode3
}
courseCodeFixed1 = courseCode1.toUpperCase.patch(4, " ", 0)
if(c2!=null)
{
    courseCodeFixed2 = c2.toUpperCase.patch(4, " ", 0)
}
if(c3!=null)
{
    courseCodeFixed3 = c3.toUpperCase.patch(4, " ", 0)
}
print(courseCodeFixed2)
print(courseCodeFixed3)

I tried implementing this solution but now it does not want to read any of my command line arguments at all

Upvotes: 0

Views: 963

Answers (2)

jwvh
jwvh

Reputation: 51271

val fileName    = args(0)
val courseCode1 = args(1).toUpperCase.patch(4, " ", 0)
val courseCode2 = args.lift(2).map(_.toUpperCase.patch(4, " ", 0))
val courseCode3 = args.lift(3).map(_.toUpperCase.patch(4, " ", 0))

You can add .getOrElse() to provide a default value if you don't want Option[String] results.

Upvotes: 2

Brandon Mott
Brandon Mott

Reputation: 61

You can use scala.util.Try to catch the index out of bounds exception and use toOption to convert Try[_] to Option[_]:

import scala.util.Try

...

val csV: Option[String] = Try(args(0)).toOption
val daY: Option[String] = Try(args(1)).toOption
val time1: Option[String] = Try(args(2)).toOption
val time2: Option[String] = Try(args(3)).toOption

Then to use the optional values you can use a for comprehension:

val newEndTime = for {
  t1 <- time1
  t2 <- time2
} yield checkLengths(t1, t2)

Upvotes: 1

Related Questions