Pramod Biligiri
Pramod Biligiri

Reputation: 365

How to define methods on specific container types in Scala?

I have a val list = List[Foo]() and I want to define certain methods on this List but only when it is of type Foo, say list.prettyDisplay().

Is that possible in Scala? I am looking at a tutorial on Advanced Types (http://twitter.github.com/scala_school/advanced-types.html) but I don't think I see what I am looking for.

Upvotes: 2

Views: 54

Answers (1)

Kim Stebel
Kim Stebel

Reputation: 42047

You can define an implicit conversion from List[Foo] to some class that implemets prettyDisplay. This conversion will not work for other lists because of the type of its parameter.

class Foo

implicit def betterFooList(l:List[Foo]) = new {
  def prettyDisplay() = ???
}

List(new Foo).prettyDisplay()

Upvotes: 4

Related Questions