代码之家  ›  专栏  ›  技术社区  ›  Wonay

如何使自定义类可用于`<-`?

  •  2
  • Wonay  · 技术社区  · 7 年前

    我不知道怎么找 <- 在线的,或者这个符号被称为什么。

    我有一节课

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

    我希望能够做到:

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

    并遍历 collection .

    我需要什么 override ?

    我已经看见了 How to make your own for-comprehension compliant scala monad? 但我不明白如何让它屈服于我 收集 .

    编辑: 感谢下面所有的答案,我能够取得一些进展。

    通过实施:

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

    和

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

    在中使用它是没有问题的。

    但是, foo 从第一个用例开始, Any 而不是 A .

    2 回复  |  直到 7 年前
        1
  •  2
  •   jwvh    7 年前

    对于单个发电机, <- 你的班级需要 map() 方法。

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

    第二台发电机也需要 flatMap() 方法。

    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
    

    当然,这些都是伪造的,毫无意义的实现,只是用来演示这个概念。

    编辑

    关于你的评论:

    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)
    
        2
  •  2
  •   Arnon Rotem-Gal-Oz    7 年前

    你至少需要实现 map 而且可能 flatMap 和 filter 至于它周围的句法糖分 the documentation

    类似的东西

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