vincent vincent - 2 months ago 16
Scala Question

how to check return value type in scala

I am pretty a fresh man to learn scala.

I want to ask how to check the function return value type?

For example :

def decode(list :List[(Int, String)]):List[String] = {

//val result = List[String]()
//list.map(l => outputCharWithTime(l._1,l._2,Nil))
//result
excuteDecode(list,List[String]())

def excuteDecode(list:List[(Int,String)],result:List[String]):List[String] = list match {
case Nil => Nil
case x::Nil=>outputCharWithTime(x._1,x._2,result)
case x::y =>excuteDecode(y,outputCharWithTime(x._1,x._2,result))
}

def outputCharWithTime(times:Int,str:String , result :List[String]):List[String]={
times match{
case 0 => result
case x => outputCharWithTime(times-1,str,str::result)
}
}

}


In this code , all the function return type is set to List[String], also created one empty List[String] parameter for excuteDecode() function .

However I get a compilation error:

Error:(128, 5) type mismatch;
found : Unit
required: List[String]
}


Anyone can tell me why there exist problem and how to check the actual return type by ourself ?

Answer

The order of statements matters here.

def decode(list :List[(Int, String)]):List[String] = {

  def excuteDecode(list:List[(Int,String)],result:List[String]):List[String] = list match {
    case Nil => Nil
    case x::Nil=>outputCharWithTime(x._1,x._2,result)
    case x::y =>excuteDecode(y,outputCharWithTime(x._1,x._2,result))
  }

  def outputCharWithTime(times:Int,str:String , result :List[String]):List[String]={
    times match{
      case 0 => result
      case x => outputCharWithTime(times-1,str,str::result)
    }
  }

  excuteDecode(list,List[String]())  // Moved here
}

In Scala, the last expression in a block defines, what the whole block returns; statements such as def are defined to produce a Unit (()).

Comments