4

In c# I can write code such as this (I ran it Linqpad 5):

void Main()
{
    new Test { Property1 = 100 }.Dump();
    Console.WriteLine(nameof(Test.Property1));
}

class Test
{
    public int Property1 { get; set; }
    override public String ToString()
    {
        return $"{nameof(Property1)}={Property1}";
    }
}

Is there a scala equivalent of nameof?

Thanks

boggy
  • 3,674
  • 3
  • 33
  • 56
  • Maybe what you want is this! Hope this can help you. [https://stackoverflow.com/questions/3105002/is-it-possible-to-recover-the-name-of-the-function-from-within-the-function-in-s](https://stackoverflow.com/questions/3105002/is-it-possible-to-recover-the-name-of-the-function-from-within-the-function-in-s) – Frank Jun 30 '17 at 00:59
  • 1
    "Property1" would work. – pedrofurla Jun 30 '17 at 01:24
  • what is scala ? – Lei Yang Jun 30 '17 at 01:57
  • @pedrofurla The benefit of `nameof` is that it is turned into a string at compile time but it otherwise still a symbol reference so can be reliably refactored with the source property. – Richard Szalay Jun 30 '17 at 02:01
  • @LeiYang A functional programming language for the JVM. http://scala-lang.org – Richard Szalay Jun 30 '17 at 02:03
  • @Frank: My goal is to avoid using magic strings. nameof in C# probably has support from the compiler. – boggy Jun 30 '17 at 02:13

2 Answers2

5

In Scala it can be done by a (macro) library instead of needing special language-level support. There is one at https://github.com/dwickern/scala-nameof.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
3

There is no any similar methods in scala as of C#, If you really want the function than you can use scala-reflection.

koiralo
  • 22,594
  • 6
  • 51
  • 72