https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

acoconut

08/30/2021, 12:47 PM
hey! do you all use some kind of code style formatter for your kotlin projects? We’re looking into it and have found the spotless plugin but i really don’t like the way ktfmt formats data classes. I think:
Copy code
data class Book (
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 val id: Long? = null
)
is way easier to read than:
Copy code
data class Book (
 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null
)
What do you all use if anything?
r

Richard Gomez

08/30/2021, 1:47 PM
I agree that the 1st is easier to read. The second makes it harder to read the field definition.
v

veluxer

08/30/2021, 2:14 PM
It is out of point but I think
entity class
is not suitable for
data class
. using
class
is better than
data class
because
entity class
use mutable property.
data class
use immutable property. also,
not nullable ID
is better then
nullable ID
so, I would write code like below.
Copy code
data class Book (
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 val id: Long = 0
)
If you use JPA, id will generate value automatically.
👍🏻 1
👍 2
r

Richard Gomez

08/30/2021, 2:21 PM
data class
 use immutable property.
@veluxer: There's nothing stopping you from using
var
instead, right?
v

veluxer

08/30/2021, 2:29 PM
It is up to developer. but I wouldn’t if I use data class for VO or DTO
m

Michael Böiers

08/30/2021, 8:42 PM
This is sufficient for me. Activating the inspection for the formatting is quite useful. https://kotlinlang.org/docs/code-style-migration-guide.html
a

acoconut

08/31/2021, 5:52 AM
Thanks Michael! And also veluxer, thanks, I will do some reading on this 🙂
c

Colton Idle

08/31/2021, 4:59 PM
Seems like ktfmt or ktlint is what most people use. ktlint has a lot of flexibility but I hit issues with it all the time to work consistently. ktfmt works really well, but I can't really customize it. Personally I prefer, 0 customization and consistent code.
In a lot of other cases ktfmt works way better than ktlint IMO
See #ktlint and #ktfmt for more. 😅
3 Views