Giter Site home page Giter Site logo

bennyhuo / kotlindeepcopy Goto Github PK

View Code? Open in Web Editor NEW
273.0 7.0 28.0 436 KB

DeepCopy extensions for Kotlin Data class. Provide Reflection, Apt, Ksp and Kcp implementations.

License: MIT License

Kotlin 99.28% Shell 0.66% Java 0.06%
kotlin dataclass deepcopy apt reflection kcp ksp

kotlindeepcopy's Introduction

License: MIT Maven Central

KotlinDeepCopy

Provide an easy way to generate DeepCopy function for data class. DeepCopy only takes effect on the component members i.e. the members declared in the primary constructor.

Reflection

Use Kotlin Reflection to provide an extension function for DeepCopyable so that any data class which implements DeepCopyable can simply call deepCopy() to copy itsself.

See the test code below:

data class Speaker(val name: String, val age: Int): DeepCopyable

data class Talk(val name: String, val speaker: Speaker): DeepCopyable

class DeepCopyTest {
    @Test
    fun test() {
        val talk = Talk("DataClass in Action", Speaker("Benny Huo", 30))
        val newTalk = talk.deepCopy()
        assert(talk == newTalk)
        assert(talk !== newTalk)
    }
}

talk equals newTalk since the values of their members are equal while they do not ref to the same object.

How to Setup

This library has been deloyed to maven center.

implementation("com.bennyhuo.kotlin:deepcopy-reflect:<latest-version>")

Apt & Ksp

If you concern about the runtime efficiency, apt may be the solution. You can simply annotate the data class you want to deep copy with a DeepCopy annotation:

@DeepCopy
data class Speaker(val name: String, val age: Int)
@DeepCopy
data class Talk(val name: String, val speaker: Speaker)

Extension function deepCopy will be generated according to the components:

fun Talk.deepCopy(name: String = this.name, speaker: Speaker = this.speaker): Talk = Talk(name, speaker.deepCopy())

fun Speaker.deepCopy(
    name: String = this.name,
    age: Int = this.age,
    company: Company = this.company
): Speaker = Speaker(name, age, company.deepCopy()) 

Notice that deepCopy is called recursively if the member type is also a data class annotated with a DeepCopy annotation. Hence, if you remove the annotation for Speaker, generated function would be like:

fun Talk.deepCopy(name: String = this.name, speaker: Speaker = this.speaker): Talk = Talk(name, speaker)

//And no deepCopy for Speaker.

How to Setup

The artifacts have been deployed to maven central repository. Set up your project by adding these lines:

plugins {
    id("com.google.devtools.ksp") version "1.9.20-1.0.14" // ksp
    id "org.jetbrains.kotlin.kapt" // kapt
}
...

dependencies {
    ksp("com.bennyhuo.kotlin:deepcopy-compiler-ksp:<latest-version>")) // ksp
    kapt("com.bennyhuo.kotlin:deepcopy-compiler-kapt:<latest-version>") // kapt
    implementation("com.bennyhuo.kotlin:deepcopy-runtime:<latest-version>")
}

KCP

This is a nearly perfect version I think. It works like copy does. You can install this IntelliJ plugin: DeepCopy and setup your project like this:

plugins {
    kotlin("jvm") version "1.9.20"
    id("com.bennyhuo.kotlin.plugin.deepcopy") version "<latest-version>"
}

dependencies {
    implementation("com.bennyhuo.kotlin:deepcopy-runtime:<latest-version>")
}

And then try to call the deepCopy function directly!

Change Log

See releases.

License

MIT License

Copyright (c) 2018 Bennyhuo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

kotlindeepcopy's People

Contributors

bennyhuo avatar jayasuryat avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

kotlindeepcopy's Issues

deepcopy-reflect-1.5.0.pom Forbidden!

集成
kapt 'com.bennyhuo.kotlin.apt:deepcopy-compiler:1.5.0'
implementation 'com.bennyhuo.kotlin.reflect:deepcopy-reflect:1.5.0'
sync now 之后
Could not GET 'https://kotlin.bintray.com/kotlinx/com/bennyhuo/kotlin/reflect/deepcopy-reflect/1.5.0/deepcopy-reflect-1.5.0.pom'. Received status code 403 from server: Forbidden
Disable Gradle 'offline mode' and sync project

访问网址提示Forbidden!

如果不加 project 仓库,会提示
Execution failed for task ':app:checkDebugAarMetadata'.

Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
Could not find com.bennyhuo.kotlin.reflect:deepcopy-reflect:1.5.0.
Searched in the following locations:
- https://dl.google.com/dl/android/maven2/com/bennyhuo/kotlin/reflect/deepcopy-reflect/1.5.0/deepcopy-reflect-1.5.0.pom
- https://repo.maven.apache.org/maven2/com/bennyhuo/kotlin/reflect/deepcopy-reflect/1.5.0/deepcopy-reflect-1.5.0.pom
- https://jcenter.bintray.com/com/bennyhuo/kotlin/reflect/deepcopy-reflect/1.5.0/deepcopy-reflect-1.5.0.pom
- https://jitpack.io/com/bennyhuo/kotlin/reflect/deepcopy-reflect/1.5.0/deepcopy-reflect-1.5.0.pom
Required by:
project :app

Possible solution:

找不到库

deepcopy.kcp-impl.plugin-ide不工作,intelij里标红

deepcopy.kcp-impl.plugin-ide,编译完之后。
本地安装了build/distributions目录里的DeepCopy-1.6.10.0-SNAPSHOT.zip

同时,deepcopy.kcp-impl.plugin-kcp publish to maven local
deepcopy.kcp-impl.plugin-gradle publish to maven local

但 deepcopy.kcp-impl.sample 工程里的talk.deepCopy() 仍然飘红!Unresolved reference: deepCopy
1

Optimize project structure

The project consists of three separated parts: Reflection, Annotation/Symbol Processing, Complier Plugin. Rearrange the modules to make it more clear.

No DeepCopy on Collections

Hi under a DeepCopy my Understandig is that even the members should be deepcopys but in this Code:

val speaker = Speaker("Benny Huo", arrayListOf(1, 2, 3, 4))
    val talk = Talk("DataClass in Action", speaker)
    val newTalk = talk.deepCopy()

    talk.speaker.arrayList.removeAt(0)

    println(talk)
    println(newTalk)

The list will change on both Objects

Import generic type argument as type

@DeepCopy
data class Hello<out P1, out P2>(
    val first: P1,
    val second: P2
)

Generated code:

import P1
import P2
import kotlin.jvm.JvmOverloads

@JvmOverloads
fun <P1, P2> Hello<P1, P2>.deepCopy(first: P1 = this.first, second: P2 = this.second): Hello<P1, P2>
        = Hello<P1, P2>(first, second) 

P1, P2 are not reified types and should not be treat as real types.

Property file name for enclosed classes.

@DeepCopy
data class Team2(val name: String, val workers: List<Worker2>, val pair: Pair<String, Worker2>, val map: Map<String, Worker2>){
    @DeepCopy
    data class Worker2(val name: String)
}

The name of the file generated is Worker2$$DeepCopy.kt which may conflict with a top-level class Worker2.

Reference to arrays is shared between original and copied object

@DeepCopy
data class ClassA(val numbers : IntArray)

This test fails because the objects shared same reference of the array, meaning that DeepCopy.kt passes same reference to the constructor in the deepCopy extension function:

@Test
fun testCopySharedIntArrayFails() {
    val a = ClassA(numbers= intArrayOf(1,2,3))
    val other = a.deepCopy()
    assertTrue(a.numbers.contentEquals(other.numbers))
    other.numbers[0] = 0
    assertFalse(a.numbers.contentEquals(other.numbers))
}

But when you use copyOf() to create copy of the array propery then the test passes.

@Test
fun testCopySharedIntArraySuccess() {
    val a = ClassA(numbers= intArrayOf(1,2,3))
    val other = a.copy(numbers = a.numbers.copyOf())
    assertTrue(a.numbers.contentEquals(other.numbers))
    other.numbers[0] = 0
    assertFalse(a.numbers.contentEquals(other.numbers))
}

Generator should do array.copyOf() for the primitive array types when calling the constructor in the deepCopy() function.

invalid format string: 'return %)('

Try to use DeepCopy, but has next error:

Caused by: java.lang.IllegalArgumentException: invalid format string: 'return %)('
	at com.squareup.kotlinpoet.CodeBlock$Builder.addArgument(CodeBlock.kt:347)
	at com.squareup.kotlinpoet.CodeBlock$Builder.add(CodeBlock.kt:317)
	at com.squareup.kotlinpoet.CodeBlock$Builder.addStatement(CodeBlock.kt:413)
	at com.squareup.kotlinpoet.FunSpec$Builder.addStatement(FunSpec.kt:441)
	at com.bennyhuo.kotlin.deepcopy.compiler.DeepCopyGenerator.generate(DeepCopyGenerator.kt:65)
	at com.bennyhuo.kotlin.deepcopy.compiler.DeepCopyProcessor.process(DeepCopyProcessor.kt:45)
	at org.jetbrains.kotlin.kapt3.base.incremental.IncrementalProcessor.process(incrementalProcessors.kt:89)
	at org.jetbrains.kotlin.kapt3.base.ProcessorWrapper.process(annotationProcessing.kt:166)
	at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:980)

Unable to resolve

Unable to resolve, fails with this error

Execution failed for task ':kspKotlin'.
> Could not resolve all files for configuration ':kspKotlinProcessorClasspath'.
   > Could not resolve com.bennyhuo.kotlin:ksp-module-support:1.7.10.2-SNAPSHOT.
     Required by:
         project :
      > Could not resolve com.bennyhuo.kotlin:ksp-module-support:1.7.10.2-SNAPSHOT.
         > Unable to load Maven meta-data from https://dimensional.jfrog.io/artifactory/maven/com/bennyhuo/kotlin/ksp-module-support/1.7.10.2-SNAPSHOT/maven-metadata.xml.
            > org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 326; The reference to entity "display" must end with the ';' delimiter.
   > Could not resolve com.bennyhuo.kotlin:ksp-module-support:1.7.10.2-SNAPSHOT.
     Required by:
         project : > com.bennyhuo.kotlin:deepcopy-compiler-ksp:1.8.20.0
      > Could not resolve com.bennyhuo.kotlin:ksp-module-support:1.7.10.2-SNAPSHOT.
         > Unable to load Maven meta-data from https://dimensional.jfrog.io/artifactory/maven/com/bennyhuo/kotlin/ksp-module-support/1.7.10.2-SNAPSHOT/maven-metadata.xml.
            > org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 326; The reference to entity "display" must end with the ';' delimiter.

耗时较长问题

目前发现一些性能不好的手机,调用这个方法耗时很长,测试的场景就是,点击一个按钮去调用一个接口,调用的接口是一个data class 封装的参数,对这个对象拷贝一下,然后去网络请求,基本都是1.5秒左右响应,网络请求最多300ms

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.