Scala自类型和泛型类 [英] Scala self-type and generic class

查看:84
本文介绍了Scala自类型和泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

abstract class Bar[M] {
  def print(t: M): Unit = {
    println(s"Bar: ${t.getClass()}")
  }
}

trait Foo[M] {
  this: Bar[M] =>
  def print2(t: M): Unit = {
    println(s"Foo: ${t.getClass()}")
  }
}

object ConcreteBar extends Bar[Int] with Foo[Int] {}
object ConcreteFooBar extends Bar[Int] with Foo[Int] {}

object Test {
  def main(args: Array[String]): Unit = {
    ConcreteBar.print(1)
    ConcreteFooBar.print2(1)
  }

在上面的示例中,有没有一种方法可以使我们不必在自定义的"bar"特征中重复该类型? 因此,我们可以这样声明ConcreteFooBar:

In the example above, is there a way so that we don't have to repeat the type in the self-typed "bar" trait? Therefore we could declare ConcreteFooBar like this:

object ConcreteFooBar extends Bar[Int] with Foo {}

推荐答案

对于Foo,您可以使用抽象类型而不是类型参数,例如:

You can use an abstract type instead of a type parameter for Foo, like this:

abstract class Bar[M] {
  type Base = M
  def print(t: M): Unit = {
    println(s"Bar: ${t.getClass()}")
  }
}

trait Foo {
  type Base
  def print2(t: Base): Unit = {
    println(s"Foo: ${t.getClass()}")
  }
}

这篇关于Scala自类型和泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆