scala

Tutorials about the Scala programming language.

Using `puts` or `echo` instead of `println` in Scala

As my mind was wandering off earlier today, I started to wonder what it would take to create a Ruby puts or PHP echo statement in Scala. (For some reason my brain can never type “println,” and puts or echo are much easier to type.)

One simple way to mimic a puts or echo method is to use Scala's ability to rename things on import:

scala> import System.out.{println => echo}
import System.out.{println=>echo}

scala> import System.out.{println => puts}
import System.out.{println=>puts}

scala> echo("foo")
foo

scala> puts("foo")
foo

scala> puts(1 + 1)
2

An example of Scala’s `f` string interpolator

With Scala it’s common to embed variables in strings like this with the s string interpolator:

val name = "Fred"
println(s"My name is $name.")

That’s cool, but when you need to format your string, Scala gives you an even more powerful tool: the f string interpolator. Here’s an example of how I just did this in my LittleLogger logging library:

Scala FAQ: Can you use a question mark to end a method name?

Scala FAQ: Can you use a question mark to end a Scala method name?

Answer: Yes, you can. Just use an underscore character before the question mark. For instance, here’s a method named alive_?:

def alive_? = true

Another possible approach you can use is to use backtick characters around the method name, without using an underscore...

Scala: How to use higher-order functions with Option (instead of match expressions)

Table of Contents1 - Sample data2 - From match expressions to higher-order functions3 - Notes4 - Resources5 - Comments

I originally wrote a long introduction to this article about Scala Options, but I decided to keep that introduction for a future second article in this series. For this article I’ll just say:

  • idiomatic Scala code involves never using null values
  • because you never use nulls, it’s important for you to become an expert at using Option, Some, and None
  • initially you may want to use match expressions to handle Option values
  • as you become more proficient with Scala and Options, you’ll find that match expressions tend to be verbose
  • becoming proficient with higher-order functions (HOFs) like map, filter, fold, and many others are the cure for that verbosity

Scala: What do “effect” and “effectful” mean in functional programming?

Table of Contents1 - Effects are related to monads2 - Not a side effect, but the main effect3 - Effectful functions return F[A] rather than [A]4 - Summary5 - Notes

When you get started with functional programming (FP) a common question you’ll have is, “What is an effect in functional programming?” You’ll hear advanced FPers use the words effects and effectful, but it can be hard to find a definition of what these terms mean.

A Scala DSL example

I was just going through some old notes and found this Scala DSL example from 2010: