5

I wrote this method:

public def getXScaleFactor(panelWidth: Int): Double = {
  return (panelWidth / (samplesContainer[0].length.asInstanceOf[Double]))
}

and I have problems with compilation:

[error] ./src/main/scala/Controllers/TrackController.scala:85: ';' expected but 'def' found.
[error]   public def getXScaleFactor(panelWidth: Int): Double {
[error]          ^

What is wrong in this code?

wattostudios
  • 8,666
  • 13
  • 43
  • 57
ciembor
  • 7,189
  • 13
  • 59
  • 100

4 Answers4

24

public is not a reserved word in Scala, so it's interpreting it as a variable name. Public access is the default; just leave off public and you'll be fine.

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
5

Methods are public by default. Remove public.

Landon Kuhn
  • 76,451
  • 45
  • 104
  • 130
4

Just to add up to the answers above:

You can also remove return keyword. The last statement/expression in a function/method is automatically the return value.

JaimeJorge
  • 1,885
  • 16
  • 15
4

The problem is that you've written Java code.

As well as public, you've also used [] for indexed access to a collection (which is invalid), an explicit return type (which isn't needed), return (which also isn't needed), and .asInstanceOf (which is unnecessary, and a code smell)

Try this for a lightweight, more idiomatic experience:

def xScaleFactor(panelWidth: Int) =
  panelWidth / samplesContainer.head.length.toDouble

Or if samplesContainer might be empty:

def xScaleFactor(panelWidth: Int) =
  panelWidth / samplesContainer.headOption.map(_.length.toDouble).getOrElse(42.0)

Put whatever you prefer in place of the default 42 there

Kevin Wright
  • 49,540
  • 9
  • 105
  • 155
  • +1 for thorough proofreading. Nothing wrong with `samplesContainer(0).length.toDouble`, though, depending on what `samplesContainer` is--an array, I'm guessing, and I wouldn't call using `head` on an array idiomatic. – Rex Kerr Jun 03 '11 at 20:22
  • Being unspecified, I'd be remiss to assume an array here, and so have to consider the most general possibility for an index-acessible collection type. `Seq` in this case. – Kevin Wright Jun 03 '11 at 21:19