user1563700
user1563700

Reputation:

Scala 2.10 Pass field as argument

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?

Upvotes: 0

Views: 514

Answers (2)

Daniel Mahler
Daniel Mahler

Reputation: 8203

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.

Upvotes: 0

David H
David H

Reputation: 1356

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

Upvotes: 1

Related Questions