dwickern / scala-nameof

Get the name of an variable, function, class member, or type as a string--at compile-time!
MIT License
131 stars 23 forks source link

Add example of usage for methods with arguments #10

Closed FunFunFine closed 3 years ago

FunFunFine commented 4 years ago

It is unclear that istead of writing full function one can use ??? to use underscore notation. For example,

case class Person(name: String, age: Int) {
   def sayHello(other: Person) = s"Hello ${other.name}!"
 }

 //most obvious way
 println(nameOf[Person](p => p.sayHello(_))

//more clear way
println(nameOf[Person](_.sayHello(???)) //note that this doesnt throw exception

This PR adds this example to README, but I guess it would be more convenient if this library would provide some other object of type Nothing to use instead of ???

dwickern commented 3 years ago

Thank you.

This PR adds this example to README, but I guess it would be more convenient if this library would provide some other object of type Nothing to use instead of ???

That's an interesting idea. We could use a placeholder marked compileTimeOnly to ensure that it's being used in a nameOf block. Anywhere else you would get a compile time error, which is an improvement over the the runtime error you'd get using ???.

@compileTimeOnly("`?` placeholder must be used in a `nameOf` block")
def ? : Nothing = ???

println(nameOf[Person](_.sayHello(?)) // "sayHello"
println(nameOf(func(?, ?, ?))) // "func"

println(func(?, ?, ?)) // compile error