简体   繁体   English

在scala中,类成员的参数化返回类型是匿名函数

[英]In scala, parameterized return type for class member that is an anonymous function

What I want is something like the following: 我想要的是以下内容:

class Foo(val f: (Bar => A) => A) {
  def consume(x: Int): Unit = {
    val myStr: String = f(bar => bar.getStr)
    val myInt: Int    = f(bar => bar.getInt)
    writeToLog(s"$myStr: ${myInt + x}")
  }
}

I know I could do this by defining a type for f with an apply method that takes type parameters. 我知道我可以通过使用带有类型参数的apply方法为f定义类型来做到这一点。 My question is can I achieve this without defining such a type? 我的问题是不定义这种类型就可以实现吗? BTW, I don't use a Bar directly because each Bar is an rpc object (eg thrift) and I have set up and tear down boilerplate code that I'm avoiding with this pattern. 顺便说一句,我不直接使用Bar ,因为每个Bar是一个rpc对象(例如,节俭),并且我已经设置和拆除了我在这种模式下避免的样板代码。

I'm not sure that it's exactly what you need, but I can suggest Polymorphic functions with Shapeless: 我不确定这是否正是您所需要的,但是我可以建议使用Shapeless的多态函数:

  import shapeless._
  import poly._

  class Bar {
    def getStr = "str"
    def getInt = 1
  }

  type Extractor[T] = Bar => T

  object extract extends Poly1 {
    implicit def caseStr = at[Extractor[String]](f => f.andThen(identity))
    implicit def caseInt = at[Extractor[Int]](f => f.andThen(identity))
  }

  class Foo(bar: Bar) {
    def e[T](f: Bar => T): Extractor[T] = f

    def consume(x: Int): Unit = {
      val myStr: String = extract(e(_.getStr)) apply bar
      val myInt: Int    = extract(e(_.getInt)) apply bar
      println(s"$myStr: ${myInt + x}")
    }
  }

  new Foo(new Bar).consume(1)

So you need to define function for each case (String, Int, etc). 因此,您需要为每种情况(字符串,整数等)定义函数。 And I used just identity. 我只使用身份。 In you example you never pass Bar, but you definitely need it at some point to calculate String and Int 在您的示例中,您永远不会传递Bar,但是在某个时候您肯定需要它来计算String和Int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM