0

Scala 2.12
What is wrong with my implementation?

object MyJob extends DatasetReader(x=x) {
  val x = "aaa"
  DatasetReader.read()
}

class DatasetReader(x: String) {
  object DatasetReader {
    def read(): String = {
       // ...
    }
  }
}

error:

super constructor cannot be passed a self reference unless parameter is declared by-name

How to fix it?

  • 3
    Can't reproduce your error "super constructor cannot be passed..." https://scastie.scala-lang.org/qc5I3DOOT02MkHPNxz1sww The error is "not found: value x". – Dmytro Mitin Nov 06 '20 at 12:18
  • Ok, maybe you have import `import MyJob.x`. Then the error is reproducible https://scastie.scala-lang.org/iXdrwmJzTtCayZibqeRIog – Dmytro Mitin Nov 06 '20 at 12:24
  • What do you want to achieve with `x=x` ? – Thilo Nov 06 '20 at 12:25
  • @Thilo I guess OP wants, using named parameter of parent constructor, to refer to object field. – Dmytro Mitin Nov 06 '20 at 12:26
  • 2
    But that object field will not be initialized yet (which is why the compiler rejects it). Do `x="aaa"` or define it as a constant somewhere else (outside of the the object that is currently being constructed). – Thilo Nov 06 '20 at 12:29
  • @Thilo Yeap, that's the reason. – Dmytro Mitin Nov 06 '20 at 12:30

2 Answers2

2

Another option you have is:

object MyJob extends {
  val x = "aaa"
} with DatasetReader(x) {
  DatasetReader.read()
}

Code run at Scastie.

There are similar post in StackOverflow, issue in github, and a bug in Scala.

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
1

Try

val x = "aaa"

object MyJob extends DatasetReader(x=x) {
  DatasetReader.read()
}

https://scastie.scala-lang.org/DjB31943QxujtmfrzLa3tg

I guess you can do what you want with early initializer

object MyJob extends {
  val x = "aaa"
} with DatasetReader(x=x) {
  DatasetReader.read()
}

https://scastie.scala-lang.org/r6FYtxXeT1SFcFHX6KFM1A

Please notice that early initializers are deprecated in Scala 3

http://dotty.epfl.ch/docs/reference/dropped-features/early-initializers.html

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66