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

[Problem] unable to get correct key name string in a for loop #25

Closed facebreeze closed 4 months ago

facebreeze commented 4 months ago

The nameOf mathod seems can not get correct key name string for the following code.

import com.github.dwickern.macros.NameOf._

object MyParam {
  val yuv400 = 0
  val yuv420 = 1
  val yuv422 = 2
  val yuv444 = 3
}
object Test extends App {
  import MyParam._
  val paramMap = Map(
    yuv400 -> 'a',
    yuv420 -> 'b',
    yuv422 -> 'c',
    yuv444 -> 'd'
  )
  for((k,v) <- paramMap) {
    println(s"k: ${nameOf(k)}, v: ${v}")
  }
}

the result will be:

k: k, v: a
k: k, v: b
k: k, v: c
k: k, v: d

as my understanding, the print should be:

k: yuv400, v: a
k: yuv420, v: b
k: yuv422, v: c
k: yuv444, v: d

So the problem is why it can not get the desired name, or if I used it in a wrong way ?

dwickern commented 4 months ago

This is expected. nameOf(k) will evaluate to "k".

To get your expected output, you could do this:

  val paramMap = Map(
    nameOf(yuv400) -> 'a',
    nameOf(yuv420) -> 'b',
    nameOf(yuv422) -> 'c',
    nameOf(yuv444) -> 'd'
  )