Skip to content

lazy val parameters and overrides #18685

@spamegg1

Description

@spamegg1

Compiler version

3.3.1

Minimized example

trait Spam:
  lazy val egg: Int

// Attempting to override a `lazy val` with a class parameter which is a `val`
class Spammy(val egg: Int) extends Spam

Output Error/Warning message

-- [E164] Declaration Error: ----------------------------------------------------------
1 |class Spammy(val egg: Int) extends Spam
  |                 ^
  |                 error overriding lazy value egg in trait Spam of type Int;
  |                   value egg of type Int must be declared lazy to override a lazy value
1 error found

Why this Error/Warning was not helpful

The message was unhelpful because... it suggests to add the lazy modifier in front of the class parameter val. But that is already not allowed:

class Spammy(lazy val egg: Int) extends Spam
//                    ^
//                    error: parameter may not be `lazy`

Suggested improvement

It could be made more helpful by... saying something like overriding a lazy val with a parameter is impossible, since the overriding value must be declared lazy but parameters cannot be lazy.

A Note on Scala 2

Scala 2 also has a related but different issue. When attempting to use a lazy val as a class parameter, it suggests using a call-by-name parameter:

// This is Scala 2.13
scala> trait Spam {
     |   val egg: Int
     | }
trait Spam

scala> class Spammy(lazy val egg: Int) extends Spam
                          ^
       error: lazy modifier not allowed here. Use call-by-name parameters instead

which suggests adding => in front of the type, but that is already not allowed for val parameters:

// This is Scala 2.13
scala> class Spammy(val egg: => Int) extends Spam
                              ^
       error: `val` parameters may not be call-by-name

It could be made more helpful by saying something like Use call-by-name parameters that are not vals instead.

I guess what I did could be considered "user error" but it's quite natural for newcomers to try these and get confused.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:reportingError reporting including formatting, implicit suggestions, etcbetter-errorsIssues concerned with improving confusing/unhelpful diagnostic messagesitype:enhancement

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions