Wonay
Wonay

Reputation: 1250

How to auto generate the with... type method in intellij

Is it possible to generate the with... type method with IntelliJ for Scala?

Example:

case class Person(name: String, age: Int)

I would like to find the tool to auto-generate the method of type:

def withName(name: String): Person = this.copy(name=name)

def withAge(age: Int): Person = this.copy(age=age)

is it possible?

Thank you.

Upvotes: 1

Views: 113

Answers (2)

francoisr
francoisr

Reputation: 4585

I you want to auto-generate these methods rather than writing them explicitly (even with an IntelliJ template), you can do that with an annotation macro that will run at compile-time.

In particular, you can check the scalameta project for informations about this. Note however that macros are an experimental feature that is likely to change in trivial ways when Scala 3 is released. In my opinion, you should think hard about whether writing withName(name) rather than copy(name=name) is worth the trouble of defining all these methods (whether its manually, through IntelliJ snippets, or using macros), and only go for macros if it will save you a lot of trouble down the line.

Upvotes: 2

Gal Naor
Gal Naor

Reputation: 2397

There is no such thing out-of-the-box, but you can create a scala template of your own:

  1. Select Settings/Preferences | Editor | Live Templates.

  2. From options on the right, open the list of Scala templates.

  3. Click + to add a new template.

You can see an example here

Upvotes: 2

Related Questions