Intellij worksheet and classes defined in it

I am following the Scala Functional Programming Curriculum course and have come up with the strange behavior of a worksheet replica.

During the course, a worksheet with the following code should give the following results on the right:

object rationals { val x = new Rational(1, 2) > x : Rational = Rational@ <hash_code> x.numer > res0: Int = 1 y. denom > res1: Int = 2 } class Rational(x: Int, y: Int) { def numer = x def denom = y } 

I get

 object rationals { > defined module rationals val x = new Rational(1, 2) x.numer y. denom } class Rational(x: Int, y: Int) { > defined class Rational def numer = x def denom = y } 

Only after moving the class to object did I get the same result as in the code.

  • Is it caused by Intellij or has there been a change in Scala?
  • Are there any other ways around this?
+5
source share
1 answer

In IntelliJ IDEA scala, a worksheet handles values ​​inside objects differently than Eclipse / Scala.

Values ​​inside objects are not evaluated in linear sequence mode; instead, they are treated like a regular scala object. You almost do not see information about this until explicit use.

To see your val and expressions, simply define or evaluate them outside of any \ class object

In some cases, this can be a savior. Suppose you have these definitions.

  val primes = 2l #:: Stream.from(3, 2).map(_.toLong).filter(isPrime) val isPrime: Long => Boolean = n => primes.takeWhile(p => p * p <= n).forall(n % _ != 0) 

Note that isPrime may be a simple def , but for some reason we decided to define it as val .

Such code is good and works in any normal scala code, but will not work on the worksheet, because val definitions are cross-references.

But it wraps such lines inside some object, for example

 object Primes { val primes = 2l #:: Stream.from(3, 2).map(_.toLong).filter(isPrime) val isPrime: Long => Boolean = n => primes.takeWhile(p => p * p <= n).forall(n % _ != 0) } 

It will be evaluated without problems.

+7
source

Source: https://habr.com/ru/post/1235615/


All Articles