Object inside class

℡╲_俬逩灬. 提交于 2021-01-29 07:41:07

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/64713535/object-inside-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!