nrinaudo / scala-best-practices

Collection of best practices for the Scala programming language

Home Page:https://nrinaudo.github.io/scala-best-practices/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`Predef.Seq` is not necessarily immutable

skolberg opened this issue · comments

Disclaimer: This has already been described here. But after visiting your scala days talk and reading the companion page, I found this kinda missing.

Say I want to write a sum function (just as an example)

def sum(nums: Seq[Int]): Int = nums.reduce(_ + _)

One could write the following code.

val nums = scala.collection.mutable.ArrayBuffer(1, 2, 3)

sum(nums)

This maybe OK in general. However, I am not sure if it should be OK.

The following code is total bogus but it illustrates that misuse is easily accomplished.

val nums = scala.collection.mutable.ArrayBuffer(1, 2, 3)

Future { sum(nums) } onComplete { println }

nums += 4

So, what's the output?

Wouldn't it be better to always explicitly require an immutable.Seq?

Agree. Although this change in 2.13, where the default imported Seq is scala.collection.immutable.Seq[A] instead of scala.collection.Seq[A]. Should markdown have metadata about the version it applies to?

Nice, I didn't know that,

Scala version in markdown metadata would (imho) only be useful if it is rendered, too. I don't know what is possible there, but a 'code comment' on top of the snippet would probably be sufficient, too.

/* ScalaVersion <= 2.12 */
...

The fact that this problem is fixed in 2.13 is not (yet) terribly relevant - a fair amount of the things I talk about are fixed or improved in 2.13, 2.14 or Dotty.

I mean, it is important, but it's a wider issue with the site - I need to somehow flag which version of Scala a rule is relevant for, not just this specific one.

I think I will add this wart, you're right. It's a trap that can definitely catch people off guard.