This page is no longer maintained — Please continue to the home page at www.scala-lang.org

view bound for AnyVal?

1 reply
Swade Leather
Joined: 2009-01-31,
User offline. Last seen 42 years 45 weeks ago.

Hi all,

Newbie Question: I'm trying to create a class parametrized by a type T
that should support the '/' operator. Is there a way to do this with
view bounds? i.e. something like this:

class Count[String, V <% AnyVal](k : String, val : V)
{
...
def norm(k : V) { val /= k; }
}

Seems like some trait should be defined in the library for AnyVal to
support this (ala Ordered[T])? Alternatively, this can be done via
inheritance...

thanks,
wade

Jon Pretty
Joined: 2009-02-02,
User offline. Last seen 42 years 45 weeks ago.
Re: view bound for AnyVal?

Hi Wade,

Swade Leather wrote:
> Newbie Question: I'm trying to create a class parametrized by a type T
> that should support the '/' operator. Is there a way to do this with
> view bounds? i.e. something like this:
>
> class Count[String, V <% AnyVal](k : String, val : V)
> {
> ...
> def norm(k : V) { val /= k; }
> }

A couple of points first:

* You can't name a parameter 'val' (it's a reserved word)
* I'm not sure whether you need the String type parameter, but I
suspect it's not necessary.
* Your current definition is shadowing the constructor parameter k with
the method parameter k in the definition of norm. This is a bad thing.
* Your definition of norm should have an equals sign between the
parameter list and the definition, otherwise it's return type will be
Unit (i.e. void).
* You don't need the semicolon.

Anyway, I think you want to do something like this:

// This is a typeclass
trait Slashable[A] {
def /(a : A, b : A) : A
// define other properties of 'slashable' things in here
}

// These are definitions for how to deal with different types as if
// they were 'slashables'...
implicit object IntSlashable extends Slashable[Int] {
def /(a : Int, b : Int) : Int = a/b
}

implicit object DoubleSlashable extends Slashable[Double] {
def /(a : Double, b : Double) : Double = a/b
}

implicit object BigIntSlashable extends Slashable[BigInteger] {
def /(a : BigInteger, b : BigInteger) = a.divide(b)
}

// ...and this is your 'Count' class
class Count[V](k : String, v : V)(implicit tc : Slashable[V]) {
def norm(w : V) = tc./(v, w)
}

This is quite a heavyweight solution for a simple case like this, but it
scales well if you're working with lots of different types, or you have
lots of operations like 'norm'.

I hope this helps,
Jon

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