简体   繁体   中英

Unable to create companion class instance in companion object method

What's wrong with this code:

class Trivials(s:String){
  private val x = 0
}

object Trivials {

  def main(args: Array[String]): Unit = {
    Trivials t = new Trivials("Trivials")
 }
}

Both class and object are defined in same source file, hence they are companion.

Error message is as: 'Cannot resolve symbol t'

Wrong syntax (You are using Java syntax) for object creation. In case of Scala you need not mention the type in front of the variable t it will be automatically inferred.

Trivials t = new Trivials("Trivials")

Scala syntax

val t = new Trivials("Trivials")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM