【问题标题】:Scala reduce returning different data typeScala减少返回不同的数据类型
【发布时间】:2018-06-12 18:31:12
【问题描述】:

我从 Java 开始使用 Scala,

此时我正在尝试解决简单的算法,基本上是hh:mm 到分钟之间的转换器,以尝试尽可能多的 scala 功能。我现在的代码是这样的(它有效)

def hourToMins(time : String):String =
  time.split(':').reduce(((a:String, b: String)=> a.toInt * 60 + b.toInt + ""))  

但是,如果我在最后删除 + "" 并将函数的返回类型更改为 Int,则不起作用

def hourToMins(time : String):Int=
  time.split(':').reduce(((a:String, b: String)=> a.toInt * 60 + b.toInt ))  
found   : (String, String) => Int  
required: (Any, Any) => Any

即使我改变它,添加一个显式转换为 Int 之类的

def hourToMins(time : String):Int=
  time.split(':').reduce(((a:String, b: String)=> (a.toInt * 60 + b.toInt ).toInt)

似乎这个版本也期望这两个参数是 Int :(

def hourToMins(time : String):Int=
   time.split(':').reduce[Int](((a:String, b: String)=> a.toInt * 60 + b.toInt )) 

不让它工作。

这样做的正确方法是什么,我做错了什么?

【问题讨论】:

    标签: scala


    【解决方案1】:

    您的列表项与结果的类型不同。 reduce 函数不允许这样做,但 foldLeft 允许。您只需要 0 作为起始值。

    "01:01".split(':').foldLeft(0) {
        (a, b) => a * 60 + b.toInt
    }
    

    这将返回 61。

    【讨论】:

      【解决方案2】:

      我会一步一步做事。

      所以先做类型转换,再做reduce。

      def hourToMins(time : String): Int = 
          time.split(':')
              .map(s => s.toInt)
              .reduce(((h, m) => h * 60 + m))
      

      【讨论】:

      • 或者甚至只是time.split(":").map(_.toInt).reduce(_ * 60 + _)
      猜你喜欢
      • 1970-01-01
      • 2015-09-28
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-18
      • 2015-12-07
      • 1970-01-01
      相关资源
      最近更新 更多