0

Team,

New to scala and learning step by step. while learning nested scopes in expression blocks, wrote below lines of code

object ExpressionTest extends App {


  val area = {
    val PI = 3.14
    PI * 10
    {
      val PI= 100
      PI * 2
    }
  }

  println(area)
}

Getting below exception at runtime .

Error:(9, 5) Int(10) does not take parameters
I am using Intellji 
Learn Hadoop
  • 2,760
  • 8
  • 28
  • 60

1 Answers1

5

In Scala it is possible to specify a function parameter as a block. The compiler thinks that your inner block is a parameter to 10 from the previous line.

To help the compiler understand what you mean, you can add a ; at the end of the line:

 val area = {
    val PI = 3.14
    PI * 10;
    {
      val PI = 100
      PI * 2
    }
  }
Kraylog
  • 7,383
  • 1
  • 24
  • 35
  • @krylog: after adding ; it is working fine as expected. Can you please provide simple example for what does it mean? "it is possible to specify a function parameter as a block." - bit confuse with functional programming – Learn Hadoop Feb 20 '19 at 07:20
  • 1
    You can, for example, write `someList.foreach { x ⇒ println(x) }` instead of `someList.foreach(x ⇒ println(x))`. That's what the parser thinks you are doing in your case. This allows you to write methods that *look like* built-in control structures, even though they are library methods. – Jörg W Mittag Feb 20 '19 at 07:33
  • There's also a comprehensive answer about parenthesis and curly braces [here](https://stackoverflow.com/questions/4386127/what-is-the-formal-difference-in-scala-between-braces-and-parentheses-and-when). – Kraylog Feb 20 '19 at 07:35
  • 1
    An empty line after `PI * 10` is more idiomatic than a semicolon. – Alexey Romanov Feb 20 '19 at 08:10