How to use scalax.io.CommandLineParser?

I want to create a class that takes a string array as a constructor argument and has command line parameter values ​​as vals members. Something like below, but I don't understand how Bistate works.

import scalax.data._
import scalax.io.CommandLineParser

class TestCLI(arguments: Array[String]) extends CommandLineParser {
    private val opt1Option = new Flag("p", "print") with AllowAll
    private val opt2Option = new Flag("o", "out") with AllowAll
    private val strOption = new StringOption("v", "value") with AllowAll
    private val result = parse(arguments)
    // true or false
    val opt1 = result(opt1Option)
    val opt2 = result(opt2Option)
    val str = result(strOption)
}
+3
source share
3 answers

Below are shorter alternatives to this pattern to get a boolean:

val opt1 = result(opt1Option).isInstanceOf[Positive[_]]
val opt2 = result(opt2Option).posValue.isDefined

The second is probably better. The posValue field is an option (there is negValue ). The isDefined method of the option indicates whether it is Some (x) or None.

+2
source

Scalax Bistate , , - . Scala (Either), , .

, Bistate Either Option, , "None -" . , Either, - :

def div(a: Int, b: Int) = if (b != 0) Left(a / b) else Right("Divide by zero")

div(4, 2) match {
  case Left(x) => println("Result: " + x)
  case Right(e) => Println("Error: " + e)
}

"Result: 2". Either . Left, , - , , Right.

+2

So, if I want to assign a variable the boolean value of whether a flag is found, should I do as shown below?

val opt1 = result(opt1Option) match {
    case Positive(_) => true
    case Negative(_) => false
}

Is there no way to write this general case with less code than this?

0
source

Source: https://habr.com/ru/post/1698939/


All Articles