简体   繁体   中英

Scala this.type conformance to type parameter bounds of supertype

I'm trying to compile the following code:

class MyClass {
  def foo(): this.type = Helper.bar(this)
}

class ChildClass extends MyClass

object Helper {
  def bar[A <: MyClass](cls: A): A = cls
}

The resulting compiler error is:

 type arguments [MyClass.this.type] do not conform to method bar's type parameter bounds [A <: MyClass]

Is there anything I can do to make this compile property with the method signatures provided above? It seems like MyClass.this.type should be a validClass, and I don't want to have to cast twice when calling Helper (once on the way in and once on the way out).

Singleton types are never inferred. You'll have to write

Helper.bar[this.type](this)

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