Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala reduce returning different data type

Tags:

scala

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?

like image 367
Marcos Miranda Beltrán Avatar asked Jun 12 '18 09:06

Marcos Miranda Beltrán


2 Answers

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.

like image 133
fafl Avatar answered Sep 25 '22 20:09

fafl


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))
like image 25
thopaw Avatar answered Sep 23 '22 20:09

thopaw