Skip to content

Context bound type parameter in def with explicit return type does not compile #1174

Closed
@agboom

Description

@agboom

The following code does not compile:

import scala.reflect.ClassTag
import scala.util._

object Main {
  class A

  def constructAs[T <: A: ClassTag]: Try[T] = Try {
    new A()
  }.flatMap {
    case inst: T => Success(inst)
    case _ =>
      val tag = implicitly[ClassTag[T]]
      Failure(new ClassCastException(s"Failed to construct instance of class ${tag.runtimeClass.getName}"))
  }
}

Dotc gives the following error:

Main.scala:10: error: type mismatch:
 found   : Main.A(inst)
 required: Nothing'
    case inst: T => Success(inst)
                            ^
one error found

If I leave out the context bound, the code compiles fine. In Scala 2.11.8 it compiles too.

Weirdly enough, if I leave out the explicit return type, it also compiles fine.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions