Defining and using expressions with def
In earlier chapters, we used the def
keyword to define variables (for example, * def myName = "Benjamin"
). However, it can be way more flexible and time-saving than that if we use it for custom functionality as well. In this section, we will explore some of these aspects.
Defining inline methods
The def
keyword allows us to define helper functions easily so that we don’t have to repeat the same calculations, string manipulations, and so on repeatedly. Here’s an example:
Scenario: Miles and kilometers * def kmToMiles = function(km) { return km / 1.6 } * def milesToKm = function(miles) { return miles * 1.6 } * assert kmToMiles(16) == 10 * def miles = kmToMiles(90) * match miles == 56.25 * match milesToKm(miles) == 90
In this example, there are two functions: kmToMiles
, which takes a km
parameter and returns the number of miles, and the milesToKm...