2016-10-01 3 views
3

私はスカラを学ぶのはかなり新鮮な人です。スカラの戻り値の型をチェックする方法

私は関数の戻り値の型をチェックする方法を尋ねたいですか?例えば

:このコードで

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) 
    } 
    } 

} 

は、全ての関数の戻り型が[文字列]を一覧表示するように設定され、またexcuteDecode()関数のために1つの空リスト[文字列]パラメータを作成しました。私は、コンパイル・エラーが発生しますが

エラー:(128、5)不一致を入力し、 が見つかりました:単位 必要:そこに問題が存在し、どのように私たち自身で実際の戻り値の型をチェックするために、なぜ一覧[文字列] }

誰も教えてもらえますか?

答えて

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())を生成するように定義されています。

+0

私は理解しています、ありがとう – vincent

関連する問題