It looks like I’m a contrarian here, but I prefer :
over with
.
Part of what I’m thinking is that if I was teaching Scala and had to introduce the following class, I would say, “Book
is a class that has two constructor parameters, title
and authors
, and it has a var
field named copiesSold
and a public method named price
”:
class Book(val title: String, val authors: ArrayBuffer[String]) {
var copiesSold = 0
def price = ???
}
So when I speak I don’t use the word “with” when talking about a class, instead I say that it “has these attributes and behaviors,” or maybe that it “contains” these. Since I don’t use with
when talking about the class, it seems a little wonky (for lack of a better term) to use it in the code. (Though “has” is arguably a synonym for “with”.) Conversely, I like that a :
can symbolize any phrase such as “has these attributes and behaviors.”
Aesthetically, IMHO, I also find that the word with
looks like it’s dangling out there by itself for small class declarations:
class Book(val title: String, val authors: ArrayBuffer[String]) with
var copiesSold = 0
def price = ???
That makes me actually prefer with:
:
class Book(val title: String, val authors: ArrayBuffer[String]) with:
var copiesSold = 0
def price = ???
But I wouldn’t want that, so if we go with with
, I think I’d always use end
to make it feel more complete:
class Book(val title: String, val authors: ArrayBuffer[String]) with
var copiesSold = 0
def price = ???
end Book
As a result of all of that, I prefer just the :
, which is more concise, and doesn’t have that dangling feeling:
class Book(val title: String, val authors: ArrayBuffer[String]):
var copiesSold = 0
def price = ???
Also, using a :
feels just like you’re writing text, like Markdown:
A Book:
- takes the parameters `title` and `authors`
- has `copiesSold`
- has `price`
In my own experience with Scala 3, :
works really well for small classes, so I don’t use end
to close the class. Then when a class starts getting longer, I do use end
, and I still like it.
Also, I don’t feel any confusion with the type ascription issue that I’ve seen other people mention. In this context I think of the :
as a container for what follows. It’s like we use =>
to mean “transformer” with HOFs and arguably with case
statements inside match
, but I don’t confuse that with using =>
for self-types.
Again, that’s just my preference. If nothing else, I thought I’d share an opposing viewpoint and the rationale behind it.