【问题标题】:how to check return value type in scala如何在scala中检查返回值类型
【发布时间】:2023-03-29 04:57:01
【问题描述】:

我是一个学习scala的新手。

请问如何查看函数返回值类型?

例如:

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) 类型不匹配; 发现:单位 必需:列表[字符串] }

谁能告诉我为什么存在问题以及如何自己检查实际的返回类型?

【问题讨论】:

    标签: scala user-defined-functions scala-collections


    【解决方案1】:

    这里的语句顺序很重要。

    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 (())。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 2021-12-13
      • 2011-07-09
      • 2013-12-16
      • 2015-09-29
      相关资源
      最近更新 更多