简体   繁体   中英

Why can't I call the Scala Seq.empty[Int]() method?

I'm trying to create a class with an attribute named _1d_matrix , which is a 1D matrix. I would want to fill it with 0.

Thus, I tried to call the method empty of the Seq object (of course not the trait), as mentionned in the documentation : http://www.scala-lang.org/api/2.12.3/scala/collection/Seq $.html#empty[A]:CC[A]

For the moment my code is :

class Calc(val width : Int) {

  private val _1d_matrix : Seq.empty[Int]()


}

But there are three errors :

  1. empty is undefined

  2. () can't be written (2 errors : "; or newline is expected" + "definition or declaration is expected")

I think it's because it's not allowed to directly make use of Seq instead of List (eg). But : why ? After all, Seq is an object (and a trait but not in my code).

Right way to initialize field looks like this:

private val _1d_matrix = Seq.empty[Int]

or

private val _1d_matrix: Seq[Int] = Seq()

There are two ways to define a 0-arity (no arguments) method in scala - with a pair of parenthesis after the name def exit() , and without one: def empty .

When it is defined in the former way, you can call it with or without parenthesis: exit() or exit - both work. But when parenthesis are not included into the method definition, you can not have them at the call site either: Seq.empty[Int] works, but Seq.empty[Int]() does not.

The convention is to use parenthesis for functions that have side effects, and not use them for purely functional calls.

The other problem with your code is that you have a : where it needs to be an assignment.

So, something like this should work:

 val _1d_matrix = Seq.empty[Int]

Your thinking is correct but you have a couple syntax errors.

private val _1d_matrix : Seq.empty[Int]()

: here is used to define a type annotation, so it's trying to find the type Seq.empty rather than the method. That fails because there is no such type.

Use = instead to assign a value. Adding the type here is optional since Scala is able to infer the correct type.

The other is that the empty method is defined without parens, so you must use Seq.empty[Int] instead of Seq.empty[Int]()

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