Scala reduce returning different data type

I am starting in Scala from Java,

At this moment I am trying to solve simple algorithms, basically, a conversor between hh:mm to mins to try as many scala features as possible. My code right now is this (It works)

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

However, if I remove the + "" at the very end and also change the return type of the function to Int, doesnt work

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

and even if I change it, adding an explicit conversion to Int like

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

it seems that this version also expects the two parameters to be Int :(

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

doesn't make it work.

What is the right way to do this and what am I doing wrong?

Upvotes: 7

Views: 3164

Answers (2)

fafl
fafl

Reputation: 7385

Your list items have a different type than the result. The reduce function does not allow this, but foldLeft does. You just need 0 as the start value.

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

This returns 61.

Upvotes: 16

thopaw
thopaw

Reputation: 4044

I would do things step after step.

So first do the type conversion then do the reduce.

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

Upvotes: 7

Related Questions