5

I am following along with a lecture, the lecturer is using Eclipse but I am using IntelliJ IDEA Community Edition 15.0.6, and the code on a Scala worksheet named rationals.scala is as follows

object rationals{
  val x = new Rational(1,2)
  x.numer
  x.denom
}

//noinspection ScalaPackageName
class Rational(x: Int, y: Int) {
  def numer = x
  def denom = y
}

The Scala worksheet worksheet will not compute and there is a warning (not error) associated with the class definition that reads

Package names doesn't correspond to directories structure, this may cause problems with resolve to classes from this file

Also, and this is odd but maybe significant, IDEA flags numer and denom as typos.

Any guidance? thx

yole
  • 92,896
  • 20
  • 260
  • 197
Max Wen
  • 737
  • 2
  • 10
  • 21
  • Isn't `object rationals` supposed to be a companion for `class Rational`? In other words, isn't there a typo? If you want for object to be a companion for the class, their names should match. – Haspemulator May 27 '16 at 09:07

2 Answers2

3

The problem isn't with the name matching directory structure, the actual problem is that you have multiple definitions in the worksheet which it doesn't like. If you declare the class inside the object, then it'll compute properly:

object rationals {
  class Rational(x: Int, y: Int) {
    def numer = x
    def denom = y
  }

  val x = new Rational(1,2)
  x.numer
  x.denom
}

IntelliJ worksheet

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • That works but I do not think that is the same thing for 2 reasons, (1) instructor demo in Eclipse does not embed class definition inside object scope but it still works, and (2) I should be able to move the class definition to a new file, Rational.scala, within the same package and reference it in the worksheet however this does not work either for same reason as original problem. – Max Wen May 26 '16 at 08:52
  • 3
    @MaxWen If you reference `Rational.scala` outside the worksheet, then you have to make sure to tick the `Make project` box the first time you run it. Eclipse and IntelliJ worksheets don't work the same. – Yuval Itzchakov May 26 '16 at 14:50
  • I am selecting this as the correct answer although I think there is something more going on. In Eclipse when you create a new worksheet foo, the new worksheet opens and object foo{} is already present. However IntelliJ opens a blank worksheet. I am thinking this indicates a difference between implementations. – Max Wen Jun 01 '16 at 02:29
3

@Yuval Itzchakov @MaxWen

If you reference Rational.scala outside the worksheet, then you have to make sure to tick the Make project box the first time you run it.

Eclipse and IntelliJ worksheets don't work the same. –

zinking
  • 5,561
  • 5
  • 49
  • 81