0

Think of a case class like this:

case class User(firstname: String, lastname: String)

now think of calling a method check with the firstname

check(User.firstname)

The Problem is, that the method check must have the name of the field too. It must have fieldname and fieldvalue -> "firstname" and "John"

The Question is, is it possible to pass the field of a class instead of its value in the style check(User.firstname)?

I thought check could look like this (preudocode):

def check(fieldName: String, fieldValue: Any) = {
    println(fieldName + ": " + fieldValue)
}

or this

def check(field: Field) = {
    println(field.getName)
}

I could pass the fieldname as String by hand but the problem is, the String would not change if I refactor the fieldname and it must match.

Maybe a macro could help? Is there any other solution?

2 Answers2

1

enter link description herefirst I assume check method is always return same type(Unit\String) else you need to use generics. second, you can use Enums for mapping

myEnum match {
  case MyEnum.firstname => myObj.firstname
  case MyEnum.lastname =>myObj.lastname 
  case _ => ....

}

if you dont want to use Enums, you will have to use scala reflection. Scala 2.10 reflection, how do I extract the field values from a case class

Community
  • 1
  • 1
David H
  • 1,346
  • 3
  • 16
  • 29
  • The problem is enum names won't change automatically when I refactor the fieldname of my class, but they must match. I could get the field with the help of reflection and the field by hand (actually I am doing this), but it would result in a very unconfortable API. –  Aug 20 '13 at 13:04
  • I cannot think about other solution. you can use Dynamic traits in order to get better api http://www.scala-lang.org/api/current/index.html#scala.Dynamic – David H Aug 20 '13 at 13:11
0

If the fieldname is known at compile time you can use macros. Otherwise you can use runtime reflection. So runtime reflection gives you more flexibility, while macros give you better performance and compile time safety.

Daniel Mahler
  • 7,653
  • 5
  • 51
  • 90