Scala Implicit Function – How to use

In this post, we are going to see how to use Scala Implicit function.

Assume we have a case class “Employee” class which contains name, age, role and location fields and we have a list of Employee case class objects. Lets see how to use Implicit function to find out the employee details by age and also by location.



case class Employee(name: String, age: Int, role: String, location: String)

class EmployeeFunction(employees: List[Employee]) {

    def findEmployeesByRole(role: String): List[Employee] ={
        employees
          .filter(e  => e.role == role)
    }

    def findEmployeesByLocation(location: String): List[Employee] ={
        employees
            .filter(e  => e.location == location)
    }

}

object EmployeeFunction {
    implicit def employeeFunction(employees: List[Employee]):EmployeeFunction = new EmployeeFunction(employees)
}


In the above code, The “EmployeeFunction” contains an implicit function “employeeFunction” defined with “implicit” keyword. So the employee list is implicitly passed to this function.

Now, to use this function in other file, we have to import this function.
Here in the below code, we import the function and then create a list of employee objects and then call “findEmployeesByRole” and “findEmployeesByLocation” methods on it.

Even though the methods findEmployeesByRole” and “findEmployeesByLocation” are not available on the List, it will call the “EmployeeFunction” class methods because of the implicit function.



import EmployeeFunction.employeeFunction

object EmployeeMain {

    def main(args: Array[String]): Unit = {

        val employees = List(Employee(name = "name0", age = 34, role = "programmer", location = "USA"),
                             Employee(name = "name1", age = 34, role = "manager", location = "USA"),
                             Employee(name = "name2", age = 34, role = "analyst", location = "USA"),
                             Employee(name = "name3", age = 33, role = "manager", location = "Canada"),
                             Employee(name = "name4", age = 34, role = "tech lead", location = "India"),
                             Employee(name = "name5", age = 37, role = "manager", location = "India"))

        println("All USA employees are\n" + employees.findEmployeesByLocation("USA"))
        println("All managers are:\n"+employees.findEmployeesByRole("manager"))

    }

}


Refer below the output of the above program



All USA employees are
List(Employee(name0,34,programmer,USA), Employee(name1,34,manager,USA), Employee(name2,34,analyst,USA))
All managers are:
List(Employee(name1,34,manager,USA), Employee(name3,33,manager,Canada), Employee(name5,37,manager,India))


Advertisements

Scala Try

The Try type in scala represents a computation that may either result in an exception, or return a successfully computed value.

In this post, We see how we can use Try type with an example.

Assume that we have a list of string and want to convert each value into number and If the value is not valid, then we have to throw an exception. We also do not want to break the program when an exception has been thrown.

Refer the below example to know how we can do that with Try type.



import scala.util.{Failure, Try}

object ScalaTryCatchExample {

    def main(args: Array[String]): Unit = {

        val values = List("1", "2", "3", "test", "5")

        values.foreach(value => {

            val tryOption = Try(convertValuesAsNumber(value))
            tryOption match {
                case Failure(e) =>
                    println(s" $value is not valid number. Exception is $e")
                case _ =>
            }
            println("Number:" + tryOption.toOption)
        }
        )

    }

    def convertValuesAsNumber(value: String): Integer = {
        if (value == null || !value.matches("[0-9]")) {
            throw new IllegalArgumentException()
        }
        Integer.valueOf(value)
    }
}


In the above Scala Object, we have “convertValuesAsNumber” method which is used to convert a string value into a number and also it throws an exception when if the value is null and not a valid number.

Here we wrap the convertValuesAsNumber method call into Try type. So when an exception throws, it would not break the program immediately. Instead the failure object is returned. So we can use match to find out this and finally call toOption method to get the value. If any exception throws then it will return a ‘None’ option.

We can also re-write the above program like below,


import scala.util.{Failure, Try}

object ScalaTryCatchExample {

    def main(args: Array[String]): Unit = {

        val values = List("1", "2", "3", "test", "5")

        values.foreach(value => {

            val tryOption = Try(Integer.valueOf(value))
            tryOption match {
                case Failure(e) =>
                    println(s" $value is not valid number. Exception is $e")
                case _ =>
            }
            println("Number:" + tryOption.toOption)
        }
        )

    }
}


The output of the above example is given below


Number:Some(1)
Number:Some(2)
Number:Some(3)
 test is not valid number. Exception is java.lang.IllegalArgumentException
Number:None
Number:Some(5)

How to use scopt(https://github.com/scopt/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 https://github.com/scopt/scopt

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.



com.ScalaApp

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

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