10 Reasons To Become A Mentor

When you imagine your idols and role models, you may sit in awe of the amazing things they are able to accomplish seemingly without much effort. You crave the same success, accolades, attention…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Using Implicit Conversions

Pragmatic Scala — by Venkat Subramaniam (52 / 140)

👈 Value Classes | TOC | Wrapping Up 👉

Let’s create a practical example of implicit conversions using string interpolators. Scala has some nice built-in string interpolators — see String Interpolation — but you can also create your own custom interpolators quite easily by using the concepts we’ve seen in this chapter. We’ll create a custom interpolator that will mask out select values from the processed string. To show that the interpolation can return something other than String — just about any object — we’ll return a StringBuilder as the result of processing the string. But first let’s revisit string interpolation to explore some concepts we need for the implementation.

When Scala sees the form

the compiler turns that into a function call on a special class named StringContext after separating the texts and the expressions. In effect, it translates the example form to

The separated-out texts are sent as arguments to the constructor of StringContext and are available through its parts property. The expressions, on the other hand, are passed as arguments to the StringContext’s method with the name of the interpolator. In the arguments sent to the constructor, each argument is a piece of text before an expression, with the last argument representing text that follows the last expression. In this example, it’s empty (“”) since there’s no text after the last expression.

As we saw earlier, the three functions that StringContext already provides are s, f, and raw. We’ll create a new interpolator named mask that will only partially display select expressions in the processed string. Let’s first use the interpolator as if it were a built-in function. Once we get a grasp of the intent from an example use, we’ll then create the interpolator.

Add a comment

Related posts:

Discover New Patterns

Patterns are born from experience. New patterns emerge every day. Some patterns might apply to a variety of systems and teams. Others might be hyper local, perhaps only applicable to a single…

Chapter 2 Taking Scala for a Ride

Our industry is moving toward functional programming, but your object-oriented experience is still valuable. Scala combines the power of OO and functional programming, and Pragmatic Scala shows you how to work effectively with both. Updated to Scala 2.11, with in-depth coverage of new features such as Akka actors, parallel colle