Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala worksheet can not resolve class name - IntelliJ IDEA

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

like image 488
Max Wen Avatar asked May 26 '16 03:05

Max Wen


People also ask

How do I create a Scala worksheet in IntelliJ?

Right-click your project and select New|Scala Worksheet. We recommend that you create an . sc file in the src directory to avoid problems with code highlighting. In the New Scala Worksheet window, type the name of the file and click OK.

How do I select Scala version in IntelliJ?

Press Ctrl+Alt+S to open Settings/Preferences dialog. From the options on the left, select Build, Execution, Deployment | Compiler | Scala | Scala Compiler Server. In JVM SDK field specify the appropriate SDK.


2 Answers

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

like image 106
Yuval Itzchakov Avatar answered Nov 10 '22 00:11

Yuval Itzchakov


@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. –

like image 3
Federico Sananes Avatar answered Nov 09 '22 23:11

Federico Sananes