简体   繁体   中英

Trait type parameters inference

Why can't the Scala compiler infer the type parameter A for Y as Int ?

trait X[A]

trait Y[A] extends X[A]

object Foo extends X[Int] with Y

Is there a way I can do this where Y can know about the type parameter of X without specifying it twice in Foo 's declaration? I couldn't get a self typing solution to work either.

For some use cases, using an intermediary class can solve the problem:

import scala.reflect.runtime.universe._

abstract class XBase {
  type A
  def say(a : A) : Unit = println(a)
}

trait Y extends XBase {
  override def say(a : A) : Unit = { 
      println("Hello ")
      super.say(a)
  }
}

class X[B : TypeTag] extends XBase {
   type A = B
}

object Foo extends X[Int] with Y

Scala does not support the inference (and omission) of type constructor parameters in type declarations. This might be possible in a future Scala version based on DOT calculus which tries to unify type parameters and type members.

See for example the slides of Odersky's talk The Trouble With Types (slides 29ff).

Do you need to have type parameter in this form? In some cases solution as following can be used:

trait X { type A /* type parameter as member */ }
trait Y extends X
object Foo extends Y { type A = Int /* equivalent to Y[Int] or X [Int] */ }

It could be used in definitions.

trait X {
  type A 
  def xfun: A
}
trait Y extends X { def tuple[K](k: K): (K, A) = (k -> xfun) }
object Foo extends Y {
  def xfun = System.identityHashCode(this)
  type A = Int
}

Then if testing:

scala> Foo.tuple("test")
res0: (String, Foo.A) = (test,2088931356)

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