2

I am in the middle of writing some code so I wanted to leave a method unimplemented which I am calling but that pathflow is not hitting based on input I am providing. The method looks like this

object HbaseStore {
  def get() = _
}

But the above code threw an exception

HbaseStore.scala:24: error: unbound placeholder parameter

[INFO] def get() = _

But when I replaced _ with ??? code executed successfully. I am just curious to know what is the difference between these two. As far as I know, _ provides default values so I assumed it would define an empty function here and return Nothing.

Community
  • 1
  • 1
Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
  • 3
    The Scala underscore, `_`, does **not** provide default values. It actually has many uses/meanings, some of which can be found [here](https://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala). – jwvh May 23 '17 at 07:41

2 Answers2

4

_ is a placeholder syntax, which is used to bind values. Placeholder syntax is used in many scenarios, for example: In case of list:

val x = List(1,2,3,4,5)
//To print each value we can do:
x.map(res => println(res)) 
//Now, we can use placeholder syntax to bind res value.
x.map(println(_)) 

Pattern matching:

val x = "some value"
x match {
case x:String => //convert to lowercase and print.
case res@_ => //here, type doesnot matter I just want to get that value and print as it is. println(res)

So, basically, you use placeholder syntax if you want to have the value without knowing its type.

On the other hand, ??? is assigned to method or variables as value in case you don't want to provide implementation.

e.g. def doSomething() => ??? here, doSomething() method is not implemented, and you need to provide or override implementation later. Note, that you cannot use variables/methods without implementations and you will get exception in case you try to invoke it. e.g. doSomething() will fail in above case.

Ra Ka
  • 2,995
  • 3
  • 23
  • 31
3

If you want to use _ as a default value you need to provide a type of this value. For example var x: Any = _ will be initialized with null but var x: Int = _ will be initialized with 0. Regarding ??? : You can click on the definition of ??? in IDE:

def ??? : Nothing = throw new NotImplementedError

Since Nothing is a subtype of any given type, it works.

simpadjo
  • 3,947
  • 1
  • 13
  • 38