What does _ :: mean mean in Scala?

I am looking through the book "Rise in Action", and I came across something that I do not quite understand: _ ::

object permanent_link extends MappedString(this, 150){ override def validations = valMinLen(3, "Link URL must be at least 5 characters") _ :: super.validations } 

I can’t find any hint, so I will be grateful if anyone can help me.

+7
source share
3 answers

I do not know the elevator, but this is a general question. First of all, :: is the Scala cons operator:

 scala> 1 :: 2 :: List(3, 4) res0: List[Int] = List(1, 2, 3, 4) 

This means that super.validations is some sequence, and valMinLen(3, "Link URL must be at least 5 characters") _ is the only value in this list.

It can be seen from the context that in the overridden validations method they call the super version and add a preliminary check at the beginning.

This additional check is created by calling valMinLen() . However, this additional call does not return an element matching the validations list type, but a function. Instead of adding the value of the function, we explicitly say (adding _ suffix`) that we want to add the function in advance, and not the return value of this function.

A code snippet is worth a thousand words:

 scala> def f = 3 f: Int scala> def g = 4 g: Int scala> val listOfInts = List(f, g) listOfInts: List[Int] = List(3, 4) scala> val listOfFunctions = List(f _, g _) listOfFunctions: List[() => Int] = List(<function0>, <function0>) 

Compare the type of listOfInts and listOfFunctions . I believe the f _ syntax is called a partially applied function in the Scala world.

+18
source

The underlined character is ignited by the fact that valMinLen is not called, but used as a pointer function.

The :: operator concatenates lists.

It would seem that the code creates a validations list, which consists of a pointer function to valMinLen with the specified parameters, and the rest of the list is the value of super.validations , that is, checking the superclass.

I'm sure someone will correct my terminology here :)

+5
source

The code may be more readable with some correct indentation and introduction of val:

 object permanent_link extends MappedString(this, 150) { override def validations = minimumValidation :: super.validations val minimumValidation = valMinLen(3,"Link URL must be at least 5 characters") _ } 

As noted earlier, the :: operator simply adds a new element to the list, _ has nothing to do with it and is used to get a function object, for example, in

 (1 :: 2 :: Nil) map (println _) 

which makes a list [1, 2] and applies the println function to each element (the underscore can really be omitted here). The println _ object creates a function object from the println method with _ representing the single parameter of the function.

0
source

All Articles