티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to create empty constructor for data class in Kotlin Android
Kotlin 안드로이드에서 데이터 클래스의 빈 생성자(empty constructor) 만들기
문제 내용
I have 10+ variables declared in Kotlin data class, and I would like to create an empty constructor for it like how we typically do in Java.
Kotlin 데이터 클래스에서 10개 이상의 변수를 선언하고 있으며, Java에서 보통하는 것처럼 빈 생성자(empty constructor)를 만들고 싶습니다.
Data class:
데이터 클래스:
data class Activity(
var updated_on: String,
var tags: List<String>,
var description: String,
var user_id: List<Int>,
var status_id: Int,
var title: String,
var created_at: String,
var data: HashMap<*, *>,
var id: Int,
var counts: LinkedTreeMap<*, *>,
)
Expected usage:
원하는 사용법:
val activity = Activity();
activity.title = "New Computer"
sendToServer(activity)
But the data class requires all arguments to be passed while creating a constructor. How can we simplify this like the Java POJO class constructor?
그러나 데이터 클래스는 생성자를 만들 때 모든 인수를 전달해야 합니다. Java POJO 클래스 생성자처럼 이를 어떻게 간단하게 할 수 있을까요?
val activity = Activity(null,null,null,null,null,"New Computer",null,null,null,null)
sendToServer(activity)
높은 점수를 받은 Solution
You have 2 options here:
두 가지 옵션이 있습니다.
data class Activity(
var updated_on: String = "",
var tags: List<String> = emptyList(),
var description: String = "",
var user_id: List<Int> = emptyList(),
var status_id: Int = -1,
var title: String = "",
var created_at: String = "",
var data: HashMap<*, *> = hashMapOf<Any, Any>(),
var id: Int = -1,
var counts: LinkedTreeMap<*, *> = LinkedTreeMap<Any, Any>()
)
data class Activity(
var updated_on: String,
var tags: List<String>,
var description: String,
var user_id: List<Int>,
var status_id: Int,
var title: String,
var created_at: String,
var data: HashMap<*, *>,
var id: Int,
var counts: LinkedTreeMap<*, *>
) {
constructor() : this("", emptyList(),
"", emptyList(), -1,
"", "", hashMapOf<Any, Any>(),
-1, LinkedTreeMap<Any, Any>()
)
}
If you don't rely on copy
or equals
of the Activity
class or don't use the autogenerated data class
methods at all you could use regular class like so:
만약 Activity 클래스의 copy나 equals에 의존하지 않거나, 자동 생성된 데이터 클래스 메소드를 전혀 사용하지 않는다면, 일반 클래스를 사용할 수 있습니다:
class ActivityDto {
var updated_on: String = "",
var tags: List<String> = emptyList(),
var description: String = "",
var user_id: List<Int> = emptyList(),
var status_id: Int = -1,
var title: String = "",
var created_at: String = "",
var data: HashMap<*, *> = hashMapOf<Any, Any>(),
var id: Int = -1,
var counts: LinkedTreeMap<*, *> = LinkedTreeMap<Any, Any>()
}
Not every DTO needs to be a data class
and vice versa. In fact in my experience I find data classes to be particularly useful in areas that involve some complex business logic.
모든 DTO가 데이터 클래스가 아니어도 되며 그 반대의 경우도 마찬가지입니다. 사실 저는 데이터 클래스가 어떤 복잡한 비즈니스 로직이 포함된 영역에서 특히 유용하다고 생각합니다.
가장 최근 달린 Solution
the modern answer for this should be using Kotlin's no-arg compiler plugin
which creates a non argument construct code for classic apies more about here
현대적인 방법은 Kotlin의 no-arg 컴파일러 플러그인을 사용하는 것입니다. 이는 고전적인 API에 대해 인수 없는 생성자 코드를 생성합니다. 더 자세한 내용은 여기를 참조하세요.
simply you have to add the plugin class path in build.gradle project level
간단히 말해, build.gradle 프로젝트 수준에 플러그인 클래스 경로를 추가한 다음,
dependencies {
....
classpath "org.jetbrains.kotlin:kotlin-noarg:1.4.10"
....
}
then configure your annotation to generate the no-arg
constructor
어노테이션을 구성하여 no-arg 생성자를 생성할 수 있습니다.
apply plugin: "kotlin-noarg"
noArg {
annotation("your.path.to.annotaion.NoArg")
invokeInitializers = true
}
then define your annotation file NoArg.kt
그리고 NoArg.kt 어노테이션 파일을 정의하면 됩니다.
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class NoArg
finally in any data class you can simply use your own annotation
마지막으로, 데이터 클래스에서 자신의 어노테이션을 사용할 수 있습니다.
@NoArg
data class SomeClass( val datafield:Type , ... )
I used to create my own no-arg
constructor as the accepted answer , which i got by search but then this plugin released or something and I found it way cleaner .
나는 검색해서 받은 답변처럼 직접 no-arg 생성자를 만들기도 했지만, 이 플러그인이 출시된 후에는 더 깔끔하게 만들 수 있다는 것을 알게 되었습니다.
출처 : https://stackoverflow.com/questions/37873995/how-to-create-empty-constructor-for-data-class-in-kotlin-android
'개발 > 안드로이드' 카테고리의 다른 글
프로그래밍 방식으로 뷰에 패딩 추가하기 (0) | 2023.03.01 |
---|---|
에뮬레이터 사용 중 "Failed to sync vcpu reg" 오류 수정하기 (0) | 2023.03.01 |
'Missing styles. Is the correct theme chosen for this layout?' 오류 수정하기 (0) | 2023.02.28 |
텍스트 뷰에서 일부 텍스트를 클릭 가능하게 설정하기 (0) | 2023.02.27 |
안드로이드에서 ImageView 안에 이미지 지우기 (0) | 2023.02.27 |