Skip to content

Spec for asInstanceOf is inconsistent (and doesn't match observed behaviour) #1447

Open
@scabug

Description

@scabug

asInstanceOf is defined as follows in the spec:

/** Type cast; needs to be inlined to work as given */ */
def asInstanceOf[A]: A = this match {
  case x: A => x
  case _ => if (this eq null) this
            else throw new ClassCastException()

Unfortunately this doesn't typecheck because "this" is not an A. If you had the bound A >: Null then returning null would work there, but of course there's no depend on this behaviour. It also doesn't correspond to observed behaviour for AnyVals, nor the specified behaviour for casting null (See section 6.3).

See #668 for past attempts to fix this and why they break. It seems that the behaviour for casting null to AnyVal types really does need to be there, but it really should be in the spec if it's going to continue behaving that way.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions