【问题标题】:Automatic type-argument inference in scalascala中的自动类型参数推断
【发布时间】:2016-12-13 19:37:31
【问题描述】:

我尝试实现一个类似的功能:

def myMap[A,B](a: Seq[A], f: A => B): Seq[B] = a.map(f)

// then I want to call it like that:
myMap(List(1,13,42), _*2)

但是对myMap 的调用无法编译,因为编译器无法推断类型参数AB。错误:missing parameter type

基本上,我希望它会推断A(Int)给定参数List(1,13,42),然后从给定f = _*2知道A推断B。但事实并非如此。

我可以做些什么来避免编写类型参数?

我发现的最好的是:

def myMap[A,B](a: Seq[A], f: A => B): Seq[B] = a.map(f)
myMap(List(1,13,42), (a: Int) => a*2)

即我在f 参数中明确给出A

【问题讨论】:

    标签: scala type-inference generic-type-argument


    【解决方案1】:

    使用多个参数列表。

    def myMap[A,B](a: Seq[A])(f: A => B): Seq[B] = a.map(f)
    
    // then call it like this:
    myMap(List(1,13,42)) (_*2)
    

    collection api 大量使用这种风格来处理foldLeft 和类似的功能。 可以查看官方风格指南here.

    【讨论】:

    • 我终于更喜欢下面的解决方案了。但你的回答更好
    【解决方案2】:

    我找到了一种方法,使用隐式类:

    implicit class MyMap[A](a: A) {
      def myMap[B](f: A => B): B = f(a)
    }
    
    // then I can call
    List(1,13,42).myMap(_*2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 2019-08-31
      • 1970-01-01
      相关资源
      最近更新 更多