1

I have a case class with two fields and a function which accepts the same arguments. Is where a way to pass contents of case class to this function without explicitly specifying all fields or ugly unapplying?

case class User(name: String, age: Int)
val user = User("Peter", 23)

def func(name: String, age: Int) = {...}

func(user.name, user.age) //works
Function.tupled(func(_,_))(User.unapply(user).get) //works, but ugly
// func(_,_) is explicit because it can be a method of a class
ov7a
  • 1,497
  • 4
  • 15
  • 34

1 Answers1

2

The simplest vanilla Scala solution is the one Tom suggested in the comments:

(func _).tupled(User.unapply(user).get)

If happen to have Shapeless in scope (maybe it's already a dependency), you could also use it to convert user to a tuple:

import shapeless._

val gen = Generic[User]
(func _).tupled(gen.to(user).tupled)
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235