Map: // write your own method that operates on a character Though the following algorithm is still short, itĭemonstrates how to create a custom method and pass that method into When the logic is complete, return whatever it is that yourĪlgorithm returns. To write a method that you can pass into map to operate on the characters in a Want to write it as a method (or function) that you can pass into the In this case, to keep your code clear, you might The map method has an implicit loop, and in thatĪlthough this algorithm it still short, imagine for a moment String, and map treats a String as a sequential collection ofĬhar elements. This is because the map method in this example is called on a Notice that the algorithm operates on one Char at a time. This example shows another way to print eachĬharacter: scala> for (c val upper = for (c "hello".foreach(println)ĭepending on your coding preferences, you can pass large blocksĮxamples demonstrate the syntax for passing an algorithm to a map method: // first example When you first start with Scala, you may not be comfortable with To convert the remaining characters to uppercase: scala> val upper = "hello, world".filter(_ != 'l').map(_.toUpper) String to create a new String with all occurrences of the lowercase In the following example, the filter method is called on the original ![]() ![]() ![]() String-you can also chain collection methods together to achieve aĭesired result. With any collection-such as a sequence of characters in a Shorten that code using the magic of Scala’s underscoreĬharacter: scala> val upper = "hello, world".map(_.toUpper) Map: scala> val upper = "hello, world".map(c => c.toUpper)Īs you’ll see in many examples throughout this book, you can Here’s a simpleĮxample of how to create an uppercase string from an input string, using Depending on your needs and preferences, you can use the map or foreach methods, a for loop, or other approaches.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |