美文网首页
kotlin 伴生对象companion object

kotlin 伴生对象companion object

作者: Bfmall | 来源:发表于2022-11-10 17:08 被阅读0次
/**
 * DESC   : 伴生对象companion object
 */
const val KtBaseObjectTest04_TAG = "KtBaseObjectTest04"

class KtCompanionObject {
    /**
     * 伴生对象:
     * 在kt中没有像java这样的static静态修饰,伴生对象很大程度上相当于java的static
     *
     */
    companion object {
        val TAG = "KtCompanionObject"
        val info ="hello lanny"

        fun showInfo() {
            Log.d(TAG, "showInfo==>info="+ info)
        }
    }
}

class KtBaseObjectTest04 {

    fun testCompanionObject01() {
        /**
         * 伴生对象,无论加载多少次,只创建一次
         * testCompanionObject01==>对象=com.xyaty.kotlinbasedemo.base05.KtCompanionObject$Companion@9c2d9c4
         * testCompanionObject01==>对象=com.xyaty.kotlinbasedemo.base05.KtCompanionObject$Companion@9c2d9c4
         * testCompanionObject01==>对象=com.xyaty.kotlinbasedemo.base05.KtCompanionObject$Companion@9c2d9c4
         *
         * testCompanionObject01==>showInfo=hello lanny
         * testCompanionObject01==>showInfo=kotlin.Unit
         * testCompanionObject01==>showInfo=kotlin.Unit
         */
        Log.d(KtBaseObjectTest04_TAG, "testCompanionObject01==>对象="+KtCompanionObject)
        Log.d(KtBaseObjectTest04_TAG, "testCompanionObject01==>对象="+KtCompanionObject)
        Log.d(KtBaseObjectTest04_TAG, "testCompanionObject01==>对象="+KtCompanionObject)
        Log.d(KtBaseObjectTest04_TAG, "testCompanionObject01==>showInfo="+KtCompanionObject.info)
        Log.d(KtBaseObjectTest04_TAG, "testCompanionObject01==>showInfo="+KtCompanionObject.showInfo())
        Log.d(KtBaseObjectTest04_TAG, "testCompanionObject01==>showInfo="+KtCompanionObject.showInfo())

        /**
         * 伴生对象背后的逻辑
         * public static final KtCompanionObject.Companion Companion = new KtCompanionObject.Companion((DefaultConstructorMarker)null);

            public static final class Companion {

            @NotNull
            public final String getTAG() {
            return KtCompanionObject.TAG;
            }

            @NotNull
            public final String getInfo() {
            return KtCompanionObject.info;
            }

            public final void showInfo() {
            Log.d(((KtCompanionObject.Companion)this).getTAG(), "showInfo==>info=" + ((KtCompanionObject.Companion)this).getInfo());
            }

            private Companion() {
            }

            // $FF: synthetic method
            public Companion(DefaultConstructorMarker $constructor_marker) {
            this();
            }
            }
         */
    }
}

相关文章

网友评论

      本文标题:kotlin 伴生对象companion object

      本文链接:https://www.haomeiwen.com/subject/ganazrtx.html