Wonay
Wonay

Reputation: 1250

How to make my custom class available for `<-`?

I don't know how to search for <- online, or what the symbol is called.

I have a class

class MyClass(collection: List[A]) {}

And I want to be able to do:

val bar = new MyClass(???)
for {
  foo <- bar
} yield ???

And iterate through the element of collection.

What do I need to override ?

I already saw How to make your own for-comprehension compliant scala monad? but I don't understand how to make it yield my collection .

Edit: Thanks to all the answers below, I was able to make some progress.

By implementing:

def map(f: A => A): MyClass

and

def flatMap(f: A => MyClass): MyClass

There is no issue with using it within a for-comprehension.

However, the type of foo, from the first use case, is Any instead of being A.

Upvotes: 2

Views: 64

Answers (2)

jwvh
jwvh

Reputation: 51271

For a single generator, <-, your class needs a map() method.

class MyClass {
  def map(f :Int => Int) :Int = 42
}
val bar = new MyClass
for {
  foo <- bar
} yield foo  //42

With a 2nd generator it also needs a flatMap() method.

class MyClass {
  def map(f :MyClass => MyClass) :MyClass = new MyClass
  def flatMap(f :MyClass => MyClass) :Int = 3
}
val bar = new MyClass
for {
  foo <- bar  //map from MyClass to MyClass
  baz <- foo  //flatMap from MyClass to Int
} yield baz   //3

These are, of course, bogus and meaningless implementations used just to demonstrate the concept.

EDIT

As to your comment:

class HiddenCollection[A](mything :List[A]) {
  def map[B](f :A => B) :List[B] = mything.map(f)
}
for {
  x <- new HiddenCollection(List('c', 'y', 'q'))
} yield x.toUpper  //res0: List[Char] = List(C, Y, Q)

Upvotes: 2

Arnon Rotem-Gal-Oz
Arnon Rotem-Gal-Oz

Reputation: 25929

you need to at least implement map and possibly flatMap and filter as for is syntactic sugar around it see the documentation

something like

   class MyClass[A](collection: List[A]){
      def map[B](f: A => B):List[B] = collection.map(f)
    }

Upvotes: 2

Related Questions