Carta Aberta

Recomendaram-me que lhe escrevesse, aproveitei que hoje acordei pensando em você. Me demorei no sono, me demorei no leito, me demorei em escrever-lhe. Não é novidade que periodicamente seu semblante…

Smartphone

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




Parameterized Types

Pragmatic Scala — by Venkat Subramaniam (40 / 140)

👈 Extending a Class | TOC | Singletons and Companions 👉

As we’ve seen, not only is extending a class concise in Scala, but it’s also streamlined to alleviate some common programming errors. Generic or parameterized types further help to create classes and functions that can work with multiple different types. The types can be specified at compile time instead of code writing time, making the code more extensible without losing type safety.

Since in Scala you can create stand-alone functions, you can create parameterized functions as well. Let’s create one:

Rather than specifying the echo function’s parameter types to be some type like Int or String, we left them open as parametric type T for the programmer to decide. The notation [T] signals to the compiler that the type T that follows is not some existing, poorly named, single-letter class but is a parameterized type.

You’d call this function much like any function, but the types of the parameters are decided at this time. Let’s call the echo function using two different types of arguments:

We passed Strings in the first call, and then Ints in the second call. The compiler accepts these with no complaint and synthesizes the function, tailored to the type of the argument. Let’s see the output:

Since we used the same type T for both the parameters, Scala will require that the arguments be of the same type. There is one gotcha, however. All types in Scala derive from Any, which we’ll see in Chapter 5, Making Use of Types. The following call will, unfortunately, work:

The result of this call shows:

If you want to prevent fellow programmers from mixing arguments of different types during refactoring, you can place a…

Add a comment

Related posts:

Tests Call the API as a User Would

Our test will deal with the entire Mastery API. This whole book has been building up to this point. This test will not exercise our code as an interior function might, rather, it will test the whole…

Talking to your computer.

Everyone uses a computer. There were over 1.5 billion computers estimated to be in use in 2015, and we can definitely believe that number has risen 5 years later. However not many people interact…

Top 17 Corporate Wellness Programs and Companies for 2022

Throughout the past year WellSteps has been involved in the wellness vendor selection process in work sites in every state. We’ve kept track of the companies that provide comprehensive wellness…