# Re: view bound for AnyVal?

2 replies
Ricky Clarkson
Joined: 2008-12-19,
A blog post I wrote[1] covers this (or at least a similar) case.  James Iry gave an excellent alternative implementation in the comments[2].

[1] http://rickyclarkson.blogspot.com/2009/01/typeclass-pattern.html
[2] http://paste.pocoo.org/show/97661/

2009/2/2 Jon Pretty <jon [dot] pretty [at] sygneca [dot] com>

> 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.
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

--
Jon Pretty | Sygneca Ltd.

Jon Pretty
Joined: 2009-02-02,
Re: view bound for AnyVal?

Ricky Clarkson wrote:
> A blog post I wrote[1] covers this (or at least a similar) case. James
> Iry gave an excellent alternative implementation in the comments[2].
>
> [2] http://paste.pocoo.org/show/97661/

Thanks, Ricky. In fact, James example is very neat, so I'd recommend
that over my own solution.

Cheers,
Jon

Joined: 2009-01-31,
Re: view bound for AnyVal?

Thanks all that was quite helpful.

On 2/2/09, Jon Pretty wrote:
>
> Ricky Clarkson wrote:
>> A blog post I wrote[1] covers this (or at least a similar) case. James
>> Iry gave an excellent alternative implementation in the comments[2].
>>
>> [2] http://paste.pocoo.org/show/97661/
>
> Thanks, Ricky. In fact, James example is very neat, so I'd recommend
> that over my own solution.
>
> Cheers,
> Jon
>
> --
> Jon Pretty | Sygneca Ltd.
>
>