Lowering points when calling a chain

I do not understand why the following code does not compile:

class Abc { def b (x : String) = x + "abc" def a (y : String) = { val ls : List[String] = y.lines toList b (ls.head) } } 

Main.scala: 8: error: type of mismatch; found: java.lang.String required: Int b (ls.head)

When I change "y.lines toList" to

 y.lines.toList 

or even

 y.lines toList; 

it compiles.

Perhaps the compiler understands this as

 (y.lines).toList(b (ls.head)) 

or something like that, but I still don't understand the rules.

+6
syntax scala
source share
2 answers

This is not obvious, and it is a combination of Scala shortcut syntax and list indexing. If you need a hint, try redefining b to:

 def b(x : String) = 0 

You will get another compiler junk, but the error will change. In short, the Scala compiler will let you omit parsers and dots for methods with a zero or one parameter parameter, and we know that b looks like it is receiving a chain. The rubbing is that Scala also uses parens for list indexing, so toList , which returns an iterator, can take one parameter as a list index. I'm definitely not sure about this part, but it seems that when you start skipping points, the lexer will become greedy, and when it comes across a method that can take one parameter, it will try to pass the next statement to it. In this case, it is a string, so it generates a syntax error.

+1
source share

You did it:

 (y.lines).toList(b (ls.head)) 

With the only possible correction:

 (y.lines).toList(b).apply(ls.head) 

I am not sure what Scala will solve in this particular case.

The rule, roughly speaking, is object (method parameters)* [method] . The compiler will continue until it finds markers for the actual expression. A ; terminates the expression, as well as a ) or } . If the next line is blank, the expression also ends. If the next line starts with a reserved keyword ( val , def , if , etc.), the expression will also end.

+1
source share

All Articles