Scala减少返回不同的数据类型

Mar*_*rán 3 scala

我从Java开始Scala,

此刻,我正在尝试解决简单的算法,基本上,在两hh:mm分钟之间进行转换以尝试尽可能多的scala功能.我的代码现在就是这个(它有效)

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

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

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

即使我改变它,添加一个显式转换为Int喜欢

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

看来这个版本也期望这两个参数是Int :(

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

不起作用.

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

faf*_*afl 8

您的列表项的类型与结果不同.该reduce功能不允许这样做,但foldLeft确实如此.你只需要0作为起始值.

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

这返回61.


tho*_*paw 6

我会一步一步做事.

首先进行类型转换然后执行reduce.

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