11/1/2022 0 Comments Scala for loop* */ object Adler32Checksum // note: Int is 32 bits, which this requires b * 65536 + a // or (b "hello". Scala for loop how to#The following example demonstrates how to call the getBytes method on a String, and then pass a block of code into aĪdler-32 checksum value on a String: package tests /** * Calculate the Adler-32 checksum using Scala. Scala> def toLower(c: Char): Char = (c.toByte+32).toCharĪs an added benefit, the same method also works with theįor/yield approach: scala> val s = "HELLO" 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 It just takes two numbers within the For loop i.e., one as the lower iteration limit and the other one as the upper iteration limit. Want to write it as a method (or function) that you can pass into the The For loops in Scala are used to serve the exact same purpose as in any other programming language, however, its functionality differs a little bit from the rest. 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 |