Contest: frontpage code snippet

Could we do a followup pattern-match to compliment this? I like the start, but it’s not really doing anything that leverages “Features” or the specific implementations.

1 Like

Hey swoogles,
Thank you for the feedback, how about the code below ?
By the way, code works on Linux and MacOs, but it does not work on Scala Fiddle and i did not test it on windows.

trait Feature 

case class ObjectOriented(description: String) extends Feature
case class Functional(description: String) extends Feature
case class StaticallyTyped(description: String) extends Feature

def colorize(feature: Feature): Feature = feature match {
    case ObjectOriented(description) =>
        ObjectOriented( s"${Console.BLUE} ${description} ${Console.RESET}" )
    case Functional(description) =>
        Functional( s"${Console.GREEN} ${description} ${Console.RESET}" )
    case StaticallyTyped(description) =>
        StaticallyTyped( s"${Console.BLUE} ${description} ${Console.RESET}" )

val scalaFeatures = List(
    ObjectOriented("Define new types and behaviors using classes and traits"),
    Functional("Define functions as values, pass them as higher-order functions or return them as curried functions"),
    StaticallyTyped("Programs are statically checked for safe and correct type usage at compile time")
1 Like

This is my contribution. It includes pattern matching, named arguments, default values, a basic ADT with case class and case object, high order functions and finally some operations on a collection.

trait State
case class Gas(noble: Boolean) extends State
case class Solid(classe: String = "unknown") extends State
case object Liquid extends State

def describe(state: State): String = state match {
  case Liquid => "an incompressible fluid"
  case Solid(classe) => s"an $classe solid"
  case Gas(noble = true) => "a noble gas"
  case Gas(noble = false) => "a simple gas"

val elements = Map("Helium" -> Gas(true), "Mercury" -> Liquid, "Calcium" -> Solid("alkaline"))

  .filterKeys(name => name != "Helium")
  .map { case (name, state) => s"The element '$name' is ${describe(state)}." }

Thanks a lot for everybody participating. I’m going to let this going until the 25th of September. Then we can do a poll to decide the winner(s).

Actually, it doesn’t work correctly on either Scalafiddle or Scastie – this is designed specifically for printing on the console, not embedded in the browser, which is the point of this particular challenge…

@jducoeur @SubMachineGhost

I just added support for colors in the console:


Something similar, but hey, I gotta try:

// default kind is "cat", because everyone loves cats
case class Animal(name: String, kind: String = "cat")

def isCat(a: Animal): Boolean =
  a.kind == "cat"

val pets = List(
  Animal("Kitty"), // default params
  Animal("Fido", "dog"),
  Animal(name = "Charlie", kind = "parrot") // named params, yay!

val catNames = pets filter(isCat) map(p => mkString(", ") // lambdas

// prints "My cats are Kitty, Tigger, Luna."
println(s"My cats are $catNames.")

@MasseGuillaume wow that was really quick (that’s what she said), thank you for the effort.

@jducoeur i’ll open an enhancement issue to support the CLI ANSI colors on the Scala Fiddle Github page, and Hopefully we’ll have that feature pretty soon.


Not really good :

Use ASCII art naming instead?

Maybe such fancy looper for parallel computing? Futures with a kind of recurrence? (I’m aware more than 18 lines)

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits._
import scala.concurrent.duration._

def loop[T, U](syncFunc: => T, heavyComputeFunc: T => Future[U], accumulator: Seq[Future[U]]): Future[Seq[U]] =
  Future {
    Looper.synchronized {
  }.flatMap { t: T =>
    val longComputation = heavyComputeFunc(t)
    loop(syncFunc, heavyComputeFunc, accumulator :+ longComputation)
  }.recoverWith {
    case _ => Future.sequence(accumulator)

// example for stream
val stream = (1 to 100).toStream.toIterator
val k = loop(
  if (stream.hasNext) else throw new RuntimeException("EOF"),
  (v: Int) => Future { Thread.sleep(834); println(v); v },
println(s"done ${Await.result(k, 20 second).sum}")

I think that the best solution is a carousel of snippets demonstrating different features of the language. See @nafg’s post above for examples.

This way readers with no background in certain field, will always find something new for them and even those who already know what all the buzz-words are about will be able to compare Scala syntax with the other languages.


I think the code snippet should be simple and don’t need to show too many features in Scala.
I find some good code examples in old Scala home page.

Some code snippets (came from here and there and modified) I like:


object HelloWorld {
  def main(args: Array[String]) {
    println("Hello, world!")
object Fib {
  def fibonacci(n: Int): Int = n match {
    case 0 | 1 => n
    case _ => fibonacci(n - 1) + fibonacci(n - 2)

  def main(args: Array[String]) {
    val numbers = List(4, 2)
    for (n <- numbers) println(fibonacci(n))


object Sort {
  def quickSort(list: List[Int]): List[Int] = list match {
    case Nil => Nil
    case head :: tail =>
      val (low, high) = tail.partition(_ < head)
      quickSort(low) ::: head :: quickSort(high)

  def main(args: Array[String]) {
    val numbers = List(6, 2, 8, 5, 1)

The third one looks good, but I still think it is a bit complex. I try to use if/else instead of pattern match (Nil is odd for beginners) but still like the latter.

1 Like

For reference, it looks like this on windows:

1 Like

I’m going to chip in and say that the front page snippet should not be to show off language features.

The goal should be two things:

  • Show how the user can do things they already know they want to do, easily

    • Create a class with fields/constructor on one line!
    • Create lists, maps and sets on one line, and iterate/etc. over them!
    • Define functions on one line!
    • Run two computations in parallel in three lines! (using Futures)
  • Show how easy it is to solve small problems

    • Fizzbuzz
    • Eight-Queens
    • Breadth-first Search
    • Sudoku
    • Make a trivial command-line app
    • Make a simple web widget

These concerns are contradictory, but neither of them involves showing off how many features the language has. It’s not an uncommon feeling that the number of features Scala has is a disadvantage of using the language!

Ideally the snippet would show no features a newbie would not immediately understand. Abstract types, multiple-inheritance/trait-stacking, context bounds, implicits, and many other things can wait for later. The example can use them just fine, but they should not be necessary for understanding what the example is doing.

That said, I’m going to throw my hat in the ring and offer the Scala.js Oscilloscope:

18 lines of non-whitespace code, uses a lot of basic language features (Seqs, anonymous functions, tuples, destructuring, for-loops) and puts together something pretty in relatively few lines of code. A user can tweak this and get immediate feedback, e.g. changing the functions used to draw the graph or changing the colors used. And anyone can appreciate the output, not just people interested in a particular algorithm or technique.

I’m also going to vote for using ScalaFiddle instead of Scastie, even though that was not the original question. Apart from ScalaFiddle compiling code way faster than Scastie, Scastie also takes forever (almost 10 seconds!) to load over here in Singapore:

It appears the fault is split between lack of full optimizations on the JS blob, as well as lack of gzip compression on the server. Apart from initial download speed, ScalaFiddle does a bunch of things Scastie doesn’t, e.g. caching compilation output using a CDN for instant initial page loads that include running the compiled output.

Overall, ScalaFiddle ends up being a much slicker experience in the places where it matters, and the shortcomings are in places where it doesn’t matter. Newbies aren’t going to care that you can’t run code using java.lang.ProcessBuilder in the “try it now!” sandbox, nor are they going to care that they can’t tweak SBT settings or compile using Dotty.

There’s a time and place for Scastie, when you want to reproduce more involved setups with custom SBT config and esoteric Scala versions. But for this use case, it seems ScalaFiddle is just the right tool for the job.


Cannot agree more, thanks for putting together this detailed explanation! :slight_smile:

Show how the user can do things they already know they want to do, easily - I agree

  • a class with fields/constructor on one line: that is an eye opener for many. IMO this should come with a remark on the number of lines in equivalent Java code, and a link to such code.

  • Sudoku: While I appreciate the elegance and conciseness of the Sudoku solver that Pathikrit posted in this thread, it also intimidates me, since I just don’t see how it works. At least it should come with a link to a page that explains the magic.


Thank for this detailed review. Your feedback points to directly actionable items.

I agree with this. Notice in the embedding above, there is no settings or anything like this. There is a run button and a button to go to Scastie. The cool thing with Scastie, it’s its extensibility. A new user might want to try a library for parsing JSON for example. We make this super easy.

We have a really cool DOM binding:

scala-js raycasting

They need to use akka.js because scalafiddle does not allow you to run JVM code by design. I don’t want to underevaluate the work that was done in akka.js, but it’s not akka. The execution model on the jvm versus the js vm is completly different.

More generally, I see This is a limitation. You should be able to use any target (JS, JVM, etc) you want.

Scastie can be a little bit slower than scalafiddle since we need to reload configuration or wait for execution on the JVM. However, it is a more general solution. It allows all possibilities of libraries and targets where scalafiddle is limited to a predefined set of libraries and Scala.js. Using sbt directly allows us to quickly enable new platforms (Scala-Native, Dotty, Typelevel Scala, etc) and evolve quickly when new Scala version are available. Lastly, It is a project supported by the Scala Center and we are committed to ensure the continuity of the projects for years to come.

It shoud be clear what the exact goal of putting a snippet of Scala on the front page is. My guess is conversion rate. The snippet should get as many visitors as possible to play around / read more about Scala, right? It doesn’t matter if we show off crazy features when the page visitor does not stay and invest more time. So in my opinion the only way to find out is measuring the conversion rate of different snippets being shown. The one with the best rate wins.


@MasseGuillaume I totally understand that there are pros and cons in both choices.
I personally think that this argumentation has fond but is biased, and I can see that there are different positions here in the community,

I will love to have the Scala site that clearly reflect the Scala community and I think that a poll on this decision will simply and effectively stop discussions and give us a strong feedback.

I’m not arguing that we will have a clear winner and I will be extremely happy if all of your arguments are felt by the the major part of the rest of the community.

B.T.W. if you and Scala Center have already taken a decision I’m wondering why it’s worth to ask people about the content, you are totally free to go your way even on this topic! :slight_smile: