What does dollar sign do in scala

后端 未结 2 1534
醉梦人生
醉梦人生 2020-12-15 16:29

When I was reading spark source code here, I saw code like $(a_variable). What does it mean?

I copy the code here:

  final val blockSize         


        
相关标签:
2条回答
  • 2020-12-15 17:03

    That isn't special Scala syntax, it's a method name. In Scala $ is a legal identifier. The method is inherited from the org.apache.spark.ml.param.Param trait.

    See the source.

    0 讨论(0)
  • 2020-12-15 17:07

    I believe that the dollar sign is usually used for string interpolation. What that means is that if I want to use a val(ue)/var(iable) inside a string (denoted with an s before the first double quotation), I can access such vals/vars using the $ sign. Otherwise, we won't be able to use vals/vars inside a string since it would not know how to escape the string characters.

    Example:

    val favoriteFruit = "strawberry"
    val strawberryCount = 12
    
    println(s"My favorite fruit is ${favoriteFruit}. I've had ${strawberryCount} pieces today!") // string interpolation
    

    In your case, however it seems that $ is a shortcut to getOrDefault the var/val (as sourced by @Michael Zajac and @kingledion...gets the value/variable. If it does not exist, gets the default value/variable). Using getOrDefault may be a more robust solution in cases in which you expect the parameter to not always have a corresponding value, for which you can set a default value.

    0 讨论(0)
提交回复
热议问题