Kotlin学习-顶层属性,顶层函数(有理解错误的,还请多多指教。)

在这里插入图片描述

package com.example.learningkotlin.day1

import android.util.Log

/**
 * @author : Maple
 * @date :2021/1/6 4:50 PM
 * @description :
 */
//顶层属性
private const val KEY_KOTLIN = "KOTLIN"
fun joinToString() {
    println("调用顶层函数")
}

/*
    这里相当于我为String类添加一个扩展函数。
    然后通过String.isHeHe() 返回一个boolean值
 */
fun String.isHeHe(): Boolean = this == "呵呵"

fun log(s: String) = Log.d("Tag", s)


//不可变扩展属性必须有get函数
val String.number: String
    get() {
        if (this == "1") {
            return "16666666666"
        } else if (this == "2") {
            return "15555555555"
        } else {
            return ""
        }
    }

//可变扩展属性必须有get set函数
var String.address: String
    get() {
        if (this == "1") {
            return "北京"
        } else if (this == "2") {
            return "上海"
        } else {
            return ""
        }
    }
    set(value) {

    }


/*
这里是编译后的java文件
public final class TopLevelKt {
   private static final String KEY_KOTLIN = "KOTLIN";

   public static final void joinToString() {
      String var0 = "调用顶层函数";
      boolean var1 = false;
      System.out.println(var0);
   }

   public static final boolean isHeHe(@NotNull String $this$isHeHe) {
      Intrinsics.checkNotNullParameter($this$isHeHe, "$this$isHeHe");
      return Intrinsics.areEqual($this$isHeHe, "呵呵");
   }

   public static final int log(@NotNull String s) {
      Intrinsics.checkNotNullParameter(s, "s");
      return Log.d("Tag", s);
   }

   @NotNull
   public static final String getNumber(@NotNull String $this$number) {
      Intrinsics.checkNotNullParameter($this$number, "$this$number");
      if (Intrinsics.areEqual($this$number, "1")) {
         return "16666666666";
      } else {
         return Intrinsics.areEqual($this$number, "2") ? "15555555555" : "";
      }
   }

   @NotNull
   public static final String getAddress(@NotNull String $this$address) {
      Intrinsics.checkNotNullParameter($this$address, "$this$address");
      if (Intrinsics.areEqual($this$address, "1")) {
         return "北京";
      } else {
         return Intrinsics.areEqual($this$address, "2") ? "上海" : "";
      }
   }

   public static final void setAddress(@NotNull String $this$address, @NotNull String value) {
      Intrinsics.checkNotNullParameter($this$address, "$this$address");
      Intrinsics.checkNotNullParameter(value, "value");
   }
}
 */
    @Test
    fun test1() {
        //调用顶层函数
        joinToString()
        println("hehe".isHeHe())
        println("呵呵".isHeHe())
        println("1".address)
        println("2".number)
    }
调用顶层函数
false
true
北京
15555555555
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值