【问题标题】:no type parameters for method flatMap方法 flatMap 没有类型参数
【发布时间】:2016-05-10 22:59:26
【问题描述】:

不知道为什么下面的代码不能编译,这是错误信息:

错误:(29, 7) 方法 flatMap 没有类型参数: (f: String => Option[B])Option[B] 存在,因此它可以应用于参数 (String => Some[Class[? 0]] forSome { type ?0 <: org.apache.hadoop.io.compress.compressioncodec> --- 因为 ---
参数表达式的类型与形参类型不兼容; 发现:String => Some[Class[?0]] forSome { type ?0 <: org.apache.hadoop.io.compress.compressioncodec> 必需:字符串 => 选项[?B]
a.flatMap(codecClassName => {
^

和代码

  def f(a: Option[String]): Unit = {
    a.flatMap(codecClassName => {
      val codecFactory = new CompressionCodecFactory(new Configuration())
      val codecClass = codecFactory.getCodecClassByName(codecClassName)
      if (codecClass == null) {
        throw new RuntimeException("Unknown or not supported codec:" + codecClassName)
      }
      Some(codecClass)
    })
  }

【问题讨论】:

    标签: scala


    【解决方案1】:

    这似乎与 getClass 和 classOf 没有返回完全相同的事实有关。详情请见Scala equivalent of Java java.lang.Class<T> Object

    四处寻找解决方法我遇到了Scala Getting class type from string representation

    那么怎么样:

    val codecClass = Manifest.classType(codecFactory.getCodecClassByName(codecClassName))
    

    【讨论】:

    • 谢谢,它有效,但我仍然不明白为什么我不能使用getClass,即使它与classOf不同,但我没有混合它们。
    【解决方案2】:

    这应该可行。 flatMap 涉及mapflatten,因此在某些情况下可能需要更多类型注释。整体代码在函数参数注释后工作,即(codecClassName: String)

    注意另一个变化——带有返回Option 类型的内部函数的flatMapmap 相同,如果该函数返回选项内部的内容(即展平选项)(见下文)。

    import org.apache.hadoop.conf.Configuration
    import org.apache.hadoop.io.compress.{CompressionCodec, CompressionCodecFactory}
    ...
      def f(a: Option[String]): Option[Class[_ <: CompressionCodec]] = {
        a.map((codecClassName: String) => {
          val codecFactory = new CompressionCodecFactory(new Configuration())
          val codecClass   = codecFactory.getCodecClassByName(codecClassName)
          if (codecClass == null) {
            throw new RuntimeException("Unknown or not supported codec:" + codecClassName)
          }
          codecClass
        })
      }
    

    如前所述显示flatMap和map之间的关系:

    scala> val opt: Option[Int] = Some(1)
    opt: Option[Int] = Some(1)
    
    scala> opt.map((i: Int) => i + 1)
    res0: Option[Int] = Some(2)
    
    scala> val opt2: Option[Int] = None
    opt2: Option[Int] = None
    
    scala> opt.flatMap((i: Int) => Some(i + 1))
    res1: Option[Int] = Some(2)
    
    scala> opt2.map((i: Int) => i + 1)
    res3: Option[Int] = None
    
    scala> opt2.flatMap((i: Int) => Some(i + 1))
    res2: Option[Int] = None
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多