Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, are semicolons necessary in some situations?

Tags:

scala

I'm studying Scala and trying to use it in my recent projects. And problems come. Here's one of my problem about necessity of semicolons. This is my example:

var str = "123.4"
var d = str toDouble
if(d > 10)
    println("Larger than 10")

These codes cannot be compiled. Because if(d > 10) println("Larger than 10") returns value and compiler thinks this value is a parameter of toDouble method. However, toDouble doesn't have a parameter. This causes error.

The easiest way to solve this is adding a semicolon at the end of line 2. Just like this:

var str = "123.4"
var d = str toDouble;
if(d > 10)
    println("Larger than 10")

This confused me and I thought I don't need semicolons at all as I won't put two statements at same line. It makes me uncomfortable that some lines end with semicolon while the others don't. Also, does it makes sense?

like image 809
Chaofan Avatar asked Apr 20 '15 08:04

Chaofan


2 Answers

Aggregating possible answers: To write same thing without syntax error you could use:

  • Semicolon

    var d = str toDouble;
    if (d > 10) println("Larger than 10")
    
  • Dot Syntax

    var d = str.toDouble
    if (d > 10)  println("Larger than 10")
    
  • Parenthesis

    var d = (str toDouble)
    if (d > 10)  println("Larger than 10")
    
  • Braces

    var d = {str toDouble}
    if (d > 10)  println("Larger than 10")
    
  • Empty line separator

    var d = str toDouble
    
    if (d > 10)  println("Larger than 10")
    

Choose the one which suits your style. But in normal (non-DSL) code you will usually meet dotted version

A [most] usual use of semicolon is inside simple for expressions with several bindings.

  for(i <- 1 to 4; j <- 1 until i) println(f"$j < $i")

Which by the way could be refactored to semicolonless version too:

  for{i <- 1 to 4
      j <- 1 until i} println(f"$j < $i")
like image 162
Odomontois Avatar answered Oct 12 '22 22:10

Odomontois


Semicolons are sometimes required when using postfix operators. This is part of the reason why postfix operators are a language feature that you'll be warned about if you haven't explicitly enabled them. You could use the str.toDouble syntax instead.

like image 30
lmm Avatar answered Oct 12 '22 23:10

lmm