Functional programming in scala5/6/2023 One (intuitive) way to use this is to chain it with the getOrElse() function as shown below - // Map of IDs vs Names val customermap: Map = Map( 11-> "CustomerA", 22->"CustomerB", 33->"CustomerC" ) customermap.get(11).getOrElse("No customer found for the provided ID")Ī very useful way of using Options is together with a collection operator like flatMap that directly handles the types for you transparently. Let's look at the Map structure's get() function signature. Option s allow for focusing on the logic flow with minimal diversions for type or exception checks.Ī standard way of using Options in Scala is for your custom functions to return Option (or Int, Long, etc.). In Java, there would be try-catch blocks that would handle thrown exceptions. In a language like Python, if None: checks would be quite common throughout the codebase. val customermap: Map = Map( 11-> "CustomerA", 22->"CustomerB", 33->"CustomerC" ) customermap.get(11) // Map's get() returns an Option customermap.get(11).get // Option's get returns the String customermap.get(999).get // Will throw a NoSuchElementException customermap.get(999).getOrElse(0) // Will return a 0 instead of throwing an exception This is best demonstrated with an example. Null types are handled a little differently in Scala - the construct used is called an Option. Most application code checks for Null/None types. import // Factorial Function Implementation that uses Tail Recursion def factorial(in_x: Double, prodsofar: Double = 1.0): Double = // syntactic sugar, where we don't have to say new Animal val doggy = Animal("dog") val kitty = Animal("cat") doggy.getConnectionParameters Options The code example below shows a tail-recursive function definition to compute the factorial of a number. In case those operators don’t meet a use case’s requirements, it’s very useful to write a tail-recursive function to operate on all the items in a collection. The recommended way to do operations on all the items in a collection is to use the operators map, flatMap, or reduce. The _ is the wildcard operator - in the case of maps and filters, it refers to the value in the collection. In the small code example below, I’m defining a list of numbers from 1 to 20, filtering on even numbers and then summing them up. When working with standard Scala collections, it’s also very intuitive to chain operators, especially with the infix notation. val examplelist: List = List(2,9,8,14) examplelist.map(x=> x * 2) // anonymous function as argument Take another function as an argument, or …Īn example of a function taking another function as an argument is the map() function in Scala's standard collections library.Photo by apoorv mittal on Unsplash Higher Order FunctionsĪs per the official documentation, Functions are first class objects in Scala, which means that they can.
0 Comments
Leave a Reply. |