了解类型成员

时间:2016-01-15 17:05:40

标签: scala

鉴于一个特点:

scala> trait Fn { 
     |  type A
     |  type B
     |  def f(x: A): B
     | }
defined trait Fn

我想用另一个Fn覆盖trait,以便:

  • 如果AString,那么B必须是Int,否则请B输入Boolean

我该怎么做?

1 个答案:

答案 0 :(得分:3)

看起来你正在考虑的类型成员比他们更多。我不认为你可以做你想要的东西,至少不是在同一个班级。

类型成员应该在最终类中定义,我不认为你可以做变量。

可以让它变得有趣:

  trait Fn {
      type A
      type B
      def f(x: A): B
     }

  implicit object Bn extends Fn {
    type A = String
    type B = Int

    def f(x: A): B = 5
  }

  implicit object Cn extends  Fn {
    type A = Int
    type B = Boolean

    def f(x: A): B = true
  }

  def fun[C](c: C)(implicit f: Fn { type A = C}) = {
    println(f.f(c))
  }


  fun[String]("H") // prints 5 (calls Bn). A = String, B = Int
  fun[Int](55)     // prints true (calls Cn). A = Int, B = Boolean
相关问题