0

Hi Given below is the code. The function Split_line returns an Array. I suppose the value splitted should be of type Array. But is considered as Unit by the Compiler. What am I doing wrong here?

object Main {

  def Split_line(line: String){
    line.split("\\|\\|")    
  }

  def main(args: Array[String]) {
    val splitted = Split_line("This is a line || hi ")
    //***I am getting error here : 'value foreach is not a member of Unit'
    splitted.foreach(println) 
  }

}
Raj
  • 2,368
  • 6
  • 34
  • 52
  • 3
    You miss an `=`. It should be `def splitLine(line:String) = {`. Besides that, I would advise to always put the return type of the function, typically to avoid this kind of errors. It's also a good practice, IMO. Closing as typographical error. – Alexis C. Apr 28 '16 at 19:54
  • 2
    @AlexisC. has it right - see http://stackoverflow.com/questions/944111/when-to-use-the-equals-sign-in-a-scala-method-declaration for more on that. In the future, please include actual text of your code in a code block, so we can easily copy and paste to try it ourselves, rather than a screenshot. – childofsoong Apr 28 '16 at 19:58

1 Answers1

1

That syntax always denotes a function returning unit. Use def Split_line(line: String) = { (with an equals) or better yet, if you are unsure, declare the return type explicitly: def Split_line(line: String): Seq[String] = {

DO note that there are even plans to remove that syntax altogether at some point: "Procedure syntax is dropped in favor of always defining functions with =".

Daniel Langdon
  • 5,899
  • 4
  • 28
  • 48
  • Using only `|` did not work for me. Got to have \\ to make it work. `|` looks like is part of regex so have to use \\ to make it work – Raj May 02 '16 at 15:30
  • oh, true, that one was a regexp and not a string separator! fine, edited :-) – Daniel Langdon May 02 '16 at 15:36