我是一个学习斯卡拉的新人。
我想问一下如何检查函数返回值类型?
例如:
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)
}
}
}
在此代码中,所有函数返回类型都设置为List [String],还为excuteDecode()函数创建了一个空的List [String]参数。
但是我收到了编译错误:
错误:(128,5)类型不匹配; 发现:单位 必需:列表[String] }
任何人都可以告诉我为什么存在问题以及如何通过自己检查实际的返回类型?
答案 0 :(得分:3)
陈述的顺序在这里很重要。
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
}
在Scala中,块中的最后一个表达式定义了整个块返回的内容; def
等语句定义为生成Unit
(()
)。