This post summarises notes and/or exercise solutions of Chapter 3 Expressions and Conditionals of Learning Scala by Jason Swartz. More complete solutions can be found HERE. Scala code is originally executed in a Eclipse Scala worksheet.
an expression is a single unit of code that returns a value
a value can be defined using expressions
an expression block has its own scope and may contain values arne variables
a statement is an expression that doesn’t return a value. eg println (which returns Unit), value/variable definitions
unlike switch, match can be used with types, regular expressions, numeric ranges and data structure contents as well as values
wildcard binding of unknown pattern
value binding of unknown pattern
matching with pattern guards
matching types with pattern variables. eg actual type can be mapped
while and do/while <- only statements, no yield
1. Given a string name, write a match expression that will return the same string if non-empty, or else the string n/a if it is empty.
2. Given a double amount, write an expression to return greater if it is more than zero, same if it equals zero, and less if it is less than zero. Can you write this with if..else blocks? How about with match expressions?
3. Write an expression to convert one of the input values cyan, magenta, yellow to their 6-char hexadecimal equivalents in string form. What can you do to handle error conditions?
4. Print the numbers 1 to 10, with each line containing a group of 5 numbers.
5. There is a popular coding interview question I’ll call typesafe, in which the numbers 1 - 100 must be printed one per line. The catch is that multiples of 3 must replace the number with the word type, while multiples of 5 must replace the number with the word safe. Of course, multiples of 15 must print typesafe.
6. Can you rewrite the answer to question 6 to fit on one line? It probably won’t be easier to read, but reducing code to its shortest form is an art, and a good exercise to learn the language.