A question about view bounds

Hi scala-user (this is my first post, be gentle :-),

Is there any way to do something like the following? If it makes any
difference, I'm not particularly tied to the syntax in Foo, but changing the
inheritance hierarchy of A/B/C would be painful :-)

class A
class B extends A
class C(val attribute: Int) extends A

class Foo[B <: A]
{
def method[X <: A <% { val attribute: Int }](x: X) =
"Has 'attribute': " + x.attribute.toString

def method(a: A) =
"No 'attribute'"
}

val foo = new Foo
println(foo.method(new B)) // No 'attribute'
println(foo.method(new C(0))) // Has 'attribute': 0

Thanks in advance!

\t

Re: A question about view bounds



On Fri, Feb 17, 2012 at 9:03 AM, Tycho Andersen <tycho [at] tycho [dot] ws> wrote:
Hi scala-user (this is my first post, be gentle :-),

Is there any way to do something like the following? If it makes any
difference, I'm not particularly tied to the syntax in Foo, but changing the
inheritance hierarchy of A/B/C would be painful :-)

class Foo[B <: A] {  def method[X <: A](x: X)(implicit ev: X <:< { val attribute: Int } = null) =      if (ev eq null) "No 'attribute'"    else "Has 'attribute': " + x.attribute}

Copyright © 2013 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland