kotlin 常用工具类

Kotlin基础——类、对象和接口 kotlin中同样使用interface关键字来定义接口,接口的含义和Java中类似,用于定义抽象使用interface关键字定义接口。实现一个接口跟Java中不同,Kotlin中继承类和实现接口都是使用冒号。重写接口中的方法,使用override关键字,与Java中不同的是,override是必须写的,如果不写则会报错。这会避免先写出实现方法再添加抽象方法造成的意外重写。和Java一样,Kotlin中的类只能继承一个类,但可以实现多个方法。 阅读详情
import android.app.Activity
import android.app.Dialog
import android.content.ClipData
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Parcel
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.annotation.*
import androidx.core.content.ContextCompat
import androidx.core.os.ParcelCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager

/**
 * Desc:Context相关拓展函数、顶层函数
 * Author: hy
 * Date: 2019/7/15 16:16
 **/

inline fun <reified T : Activity> Fragment.startActivity(vararg params: Pair<String, Any?>) =
        activity?.let {
            Internals.internalStartActivity(it, T::class.java, params)
        }

inline fun <reified T : Activity> Context.startActivity(vararg params: Pair<String, Any?>) =
        Internals.internalStartActivity(this, T::class.java, params)

inline fun <reified T : Activity> Activity.startActivity(vararg params: Pair<String, Any?>) =
        Internals.internalStartActivity(this, T::class.java, params)

inline fun <reified T : Activity> Fragment.startActivityForRes(requestCode: Int, vararg params: Pair<String, Any?>) =
        activity?.let {
            startActivityForResult(Internals.createIntent(it, T::class.java, params), requestCode)
        }

inline fun <reified T : Activity> Activity.startActivityForRes(requestCode: Int, vararg params: Pair<String, Any?>) =
        startActivityForResult(Internals.createIntent(this, T::class.java, params), requestCode)

fun Context.getDrawableByAttr(@AttrRes attr: Int): Drawable? {
    val ta = obtainStyledAttributes(intArrayOf(attr))
    val drawable = ta.getDrawable(0)
    ta.recycle()
    return drawable
}

fun Context.getThemeByAttr(@AttrRes attr: Int): Int {
    val ta = obtainStyledAttributes(intArrayOf(attr))
    val theme = ta.getResourceId(0, 0)
    ta.recycle()
    return theme
}

/**
 * 复制到粘贴板
 */
/*fun Context.copyText(string: String) {
    val cm = getSystemService(Context.CLIPBOARD_SERVICE)
            as android.content.ClipboardManager
    val clip = ClipData.newPlainText("", string)
    cm.primaryClip = clip
}*/


fun Context.getString(@StringRes id: Int): String = getString(id)

fun Fragment.inflate(@LayoutRes id: Int, root: ViewGroup? = null, attachToRoot: Boolean = false): View = LayoutInflater.from(context).inflate(id, root, attachToRoot)

fun Activity.inflate(@LayoutRes id: Int, root: ViewGroup? = null, attachToRoot: Boolean = false): View = LayoutInflater.from(this).inflate(id, root, attachToRoot)

fun View.inflate(@LayoutRes id: Int, root: ViewGroup? = null, attachToRoot: Boolean = false): View = LayoutInflater.from(this.context).inflate(id, root, attachToRoot)

fun Fragment.horizontalLinearLayoutManager() = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)

fun Fragment.verticalLinearLayoutManager() = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)

fun Fragment.gridLayoutManager(spanCount: Int) = GridLayoutManager(context, spanCount)

fun Activity.horizontalLinearLayoutManager() = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)

fun Activity.verticalLinearLayoutManager() = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

fun Activity.gridLayoutManager(spanCount: Int) = GridLayoutManager(this, spanCount)

fun Context.horizontalLinearLayoutManager() = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)

fun Context.verticalLinearLayoutManager() = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

fun Context.gridLayoutManager(spanCount: Int) = GridLayoutManager(this, spanCount)

fun View.findColor(@ColorRes corRes: Int): Int = ContextCompat.getColor(context, corRes)
fun Fragment.findColor(@ColorRes corRes: Int): Int = ContextCompat.getColor(context!!, corRes)
fun Context.findColor(@ColorRes id: Int): Int = ContextCompat.getColor(this, id)
fun Activity.findColor(@ColorRes id: Int): Int = ContextCompat.getColor(this, id)

/**
 * 返回contentView
 */
inline val Activity.contentView: View?
    get() = findOptional<ViewGroup>(android.R.id.content)?.getChildAt(0)

inline fun <reified T : View> View.find(@IdRes id: Int): T = findViewById(id)
inline fun <reified T : View> Activity.find(@IdRes id: Int): T = findViewById(id)
inline fun <reified T : View> Fragment.find(@IdRes id: Int): T = view?.findViewById(id) as T
inline fun <reified T : View> Dialog.find(@IdRes id: Int): T = findViewById(id)

inline fun <reified T : View> View.findOptional(@IdRes id: Int): T? = findViewById(id) as? T
inline fun <reified T : View> Activity.findOptional(@IdRes id: Int): T? = findViewById(id) as? T
inline fun <reified T : View> Fragment.findOptional(@IdRes id: Int): T? = view?.findViewById(id) as? T
inline fun <reified T : View> Dialog.findOptional(@IdRes id: Int): T? = findViewById(id) as? T

fun <T : Fragment> T.withArguments(params: Array<out Pair<String, Any?>>): T {
    arguments = Internals.bundleOf(params)
    return this
}


/**
 * 显示软键盘
 */
fun View.showSoftInput() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    postDelayed({
        requestFocus()
        imm.showSoftInput(this, InputMethodManager.SHOW_FORCED)
    }, 60)
}

/**
 * 隐藏软键盘
 */
fun View.hideSoftInput() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(this.windowToken, 0)
}

fun Activity.hideSoftInput() {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    if (currentFocus != null) {
        imm.hideSoftInputFromWindow(currentFocus!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }
}

/** Write a boolean to a Parcel. */
fun Parcel.writeBooleanUsingCompat(value: Boolean) = ParcelCompat.writeBoolean(this, value)

/** Read a boolean from a Parcel. */
fun Parcel.readBooleanUsingCompat() = ParcelCompat.readBoolean(this)

上面代码关联的Internals,实际跳转逻辑

import android.app.Activity
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import java.io.Serializable

/**
 * Desc:
 * Author: hy
 * Date: 2019/7/15 16:54
 **/

object Internals {

    @JvmStatic
    fun <T> createIntent(ctx: Context, clazz: Class<out T>, params: Array<out Pair<String, Any?>>): Intent {
        val intent = Intent(ctx, clazz)
        if (params.isNotEmpty()) fillIntentArguments(intent, params)
        return intent
    }

    @JvmStatic
    fun internalStartActivity(
            ctx: Context,
            activity: Class<out Activity>,
            params: Array<out Pair<String, Any?>>
    ) {
        ctx.startActivity(createIntent(ctx, activity, params))
    }

    @JvmStatic
    fun internalStartActivityForResult(
            act: Activity,
            activity: Class<out Activity>,
            requestCode: Int,
            params: Array<out Pair<String, Any?>>
    ) {
        act.startActivityForResult(createIntent(act, activity, params), requestCode)
    }

    @JvmStatic
    fun internalStartService(
            ctx: Context,
            service: Class<out Service>,
            params: Array<out Pair<String, Any?>>
    ): ComponentName? = ctx.startService(createIntent(ctx, service, params))

    @JvmStatic
    fun internalStopService(
            ctx: Context,
            service: Class<out Service>,
            params: Array<out Pair<String, Any?>>
    ): Boolean = ctx.stopService(createIntent(ctx, service, params))

    @JvmStatic
    private fun fillIntentArguments(intent: Intent, params: Array<out Pair<String, Any?>>) {
        params.forEach {
            when (val value = it.second) {
                null -> intent.putExtra(it.first, null as Serializable?)
                is Int -> intent.putExtra(it.first, value)
                is Long -> intent.putExtra(it.first, value)
                is CharSequence -> intent.putExtra(it.first, value)
                is String -> intent.putExtra(it.first, value)
                is Float -> intent.putExtra(it.first, value)
                is Double -> intent.putExtra(it.first, value)
                is Char -> intent.putExtra(it.first, value)
                is Short -> intent.putExtra(it.first, value)
                is Boolean -> intent.putExtra(it.first, value)
                is Serializable -> intent.putExtra(it.first, value)
                is Bundle -> intent.putExtra(it.first, value)
                is Parcelable -> intent.putExtra(it.first, value)
                is Array<*> -> when {
                    value.isArrayOf<CharSequence>() -> intent.putExtra(it.first, value)
                    value.isArrayOf<String>() -> intent.putExtra(it.first, value)
                    value.isArrayOf<Parcelable>() -> intent.putExtra(it.first, value)
                    else -> throw Exception("Intent extra ${it.first} has wrong type ${value.javaClass.name}")
                }
                is IntArray -> intent.putExtra(it.first, value)
                is LongArray -> intent.putExtra(it.first, value)
                is FloatArray -> intent.putExtra(it.first, value)
                is DoubleArray -> intent.putExtra(it.first, value)
                is CharArray -> intent.putExtra(it.first, value)
                is ShortArray -> intent.putExtra(it.first, value)
                is BooleanArray -> intent.putExtra(it.first, value)
                else -> throw Exception("Intent extra ${it.first} has wrong type ${value.javaClass.name}")
            }
            return@forEach
        }
    }

    fun bundleOf(params: Array<out Pair<String, Any?>>): Bundle {
        val b = Bundle()
        for (p in params) {
            val (k, v) = p
            when (v) {
                null -> b.putSerializable(k, null)
                is Boolean -> b.putBoolean(k, v)
                is Byte -> b.putByte(k, v)
                is Char -> b.putChar(k, v)
                is Short -> b.putShort(k, v)
                is Int -> b.putInt(k, v)
                is Long -> b.putLong(k, v)
                is Float -> b.putFloat(k, v)
                is Double -> b.putDouble(k, v)
                is String -> b.putString(k, v)
                is CharSequence -> b.putCharSequence(k, v)
                is Parcelable -> b.putParcelable(k, v)
                is Serializable -> b.putSerializable(k, v)
                is BooleanArray -> b.putBooleanArray(k, v)
                is ByteArray -> b.putByteArray(k, v)
                is CharArray -> b.putCharArray(k, v)
                is DoubleArray -> b.putDoubleArray(k, v)
                is FloatArray -> b.putFloatArray(k, v)
                is IntArray -> b.putIntArray(k, v)
                is LongArray -> b.putLongArray(k, v)
                is Array<*> -> {
                    @Suppress("UNCHECKED_CAST")
                    when {
                        v.isArrayOf<Parcelable>() -> b.putParcelableArray(k, v as Array<out Parcelable>)
                        v.isArrayOf<CharSequence>() -> b.putCharSequenceArray(k, v as Array<out CharSequence>)
                        v.isArrayOf<String>() -> b.putStringArray(k, v as Array<out String>)
                        else -> throw Exception("Unsupported bundle component (${v.javaClass})")
                    }
                }
                is ShortArray -> b.putShortArray(k, v)
                is Bundle -> b.putBundle(k, v)
                else -> throw Exception("Unsupported bundle component (${v.javaClass})")
            }
        }
        return b
    }


}


和屏幕相关工具类

import android.content.Context
import android.content.res.Resources
import android.util.TypedValue

/**
 * Desc:
 * Author: hy
 * Date: 2019/4/8 14:54
 **/

private val displayMetrics = Resources.getSystem().displayMetrics

val Float.dp: Float
    @JvmName("dp2px")
    get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, displayMetrics)

val Int.dp: Int
    @JvmName("dp2px")
    get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), displayMetrics).toInt()

val Float.sp: Float
    @JvmName("sp2px")
    get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this, displayMetrics)

val Int.sp: Int
    @JvmName("sp2px")
    get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this.toFloat(), displayMetrics).toInt()

val Number.px: Number
    get() = this

val Number.px2dp: Int
    @JvmName("px2dp")
    get() = (this.toFloat() / displayMetrics.density).toInt()

val Number.px2sp: Int
    @JvmName("px2sp")
    get() = (this.toFloat() / displayMetrics.scaledDensity).toInt()

val SCREEN_WIDTH: Int
    @JvmName("SCREEN_WIDTH")
    get() = displayMetrics.widthPixels

val SCREEN_HEIGHT: Int
    @JvmName("SCREEN_HEIGHT")
    get() = displayMetrics.heightPixels

val STATUS_BAR_HEIGHT: Int
    @JvmName("STATUS_BAR_HEIGHT")
    get() {
        val resourceId = Resources.getSystem().getIdentifier("status_bar_height", "dimen", "android")
        return Resources.getSystem().getDimensionPixelSize(resourceId)
    }

val Context.ACTION_BAR_HEIGHT: Int
    @JvmName("ACTION_BAR_HEIGHT")
    get() {
        val tv = TypedValue()
        return if (theme.resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            TypedValue.complexToDimensionPixelSize(tv.data, resources.displayMetrics)
        } else 0
    }
val NAVIGATION_BAR_HEIGHT: Int
    @JvmName("NAVIGATION_BAR_HEIGHT")
    get() {
        val resourceId = Resources.getSystem().getIdentifier("navigation_bar_height", "dimen", "android")
        return if (resourceId != 0) {
            Resources.getSystem().getDimensionPixelOffset(resourceId)
        } else {
            0
        }
    }

Android开发者的 Kotlin 核心要点指南:变量、函数扩展与实用技巧 Google I/O 2017宣布Kotlin成为Android官方一级开发语言。文章介绍了Kotlin在Android Studio中的配置方法,包括Gradle设置,并详细讲解了Kotlin的核心特性:变量定义(val/var)、非空类型、函数扩展、Parcelable序列化实现。通过Toast工具类和Activity跳转示例,展示了Kotlin的伴生对象替代Java静态方法、属性委托等语法特点。最后提供代码下载链接,帮助开发者快速上手Kotlin的Android开发。 阅读详情

相关推荐

kotlin 加密算法工具类

包含了: AES加密算法 DES加密算法 CBC/ ECB加密模式 MD5加密算法 RSA加密算法 SHA1加密算法 SHA256加密算法

扩展函数工具类篇(Kotlin)

android koltin 扩展工具类(笔记)

BirdEatBug的博客 1826

EduCoder 计算机网络实验 IP协议分析

第1关:跟踪抓包 任务描述 相关知识 IPV4数据包 截获数据报 分析截获结果 使用git将本地文件推送到远程仓库永久保存 操作要求 任务描述 本关任务:使用 Ping 命令发送数据报,用 Wireshark 截获数据报,分析 IP 数据报的格式,理解 IPV4 地址的编址方法,加深对 IP 协议的理解。 相关知识 为了完成本关任务,你需要掌握: 截获数据报; 简单分析数据包格式。 IPV4数据包 网际协议第 4 版(Internet Protocol version 4

qq_41975868的博客 1万+

Kotlin 常用工具类

工具类一般方式为扩展函数,这里列的内容不多,如果有建议或者好的项目,欢迎留言。 与Context有关工具类 import android.app.Activity import android.app.Dialog import android.content.ClipData import android.content.Context import android.graphics.drawable.Drawable import android.os.Parcel import android.vie

feipengwang的博客 1730

CPU也能跑大模型?手把手教你用vLLM离线部署Qwen2.5-7B-Instruct(附性能优化技巧)

本文详细介绍了如何在CPU服务器上高效部署Qwen2.5-7B-Instruct模型,通过vLLM框架和一系列优化技巧实现离线推理。内容包括环境配置、模型加载优化、性能调优及生产环境部署方案,帮助开发者在资源有限的情况下也能运行大语言模型。

weixin_28691741的博客 502

Matlab R2024a硬件支持包安装避坑指南:以Arduino为例(附离线包下载)

本文详细介绍了Matlab R2024a硬件支持包(Support Package)的安装流程,特别是针对Arduino平台的避坑指南和高效部署方法。从环境准备、离线安装方案到Arduino支持包的专项优化,提供了全面的技术细节和解决方案,帮助开发者避免常见错误,实现快速部署。

weixin_33737134的博客 459

kotlin常用工具类总结,高效优雅的开发Android

  随着Kotlin的普及,很有必要对开发中常用的工具类总结整理,当然包括 利用kotlin扩展Android原生控件方法、属性。 主要分工具类util跟原生控件扩展ext两部分 toast 用法 toast(“hello”) click 用法 button.click{ // todo } 启动activity start+要启动的activity (比如 DemoActivity...

weixin_43137158的博客 1776

别再折腾老教程了!树莓派4B/5最新系统(Raspberry Pi OS Bookworm)红外遥控配置,用gpio-ir驱动一次成功

本文详细介绍了树莓派4B/5在最新Raspberry Pi OS Bookworm系统下配置红外遥控的完整指南,摒弃过时的lirc-rpi驱动,采用现代gpio-ir驱动方案。从硬件连接到软件配置,提供10分钟快速上手指南,涵盖驱动加载、信号测试、按键映射及高级应用场景,帮助用户高效完成红外遥控配置。

weixin_42520909的博客 449

使用kotlin开发常用工具类

1.包装LogUtils(只包装了e级别和v级别), object LogUtils { val isDebug: Boolean = true /** *包装log.e日志 */ fun e(tag: String, msg: String) { if(isDebug){ Log.e(tag,msg)

qq_19463589的博客 2432

TruckSim与Simulink联合仿真中的车轮转角精确控制策略

本文深入探讨了TruckSim与Simulink联合仿真中实现车轮转角精确控制的关键策略。针对多轴车辆路径跟踪时转角指令失灵的常见问题,核心在于正确配置TruckSim转向轴的外部输入模式(Advanced Settings),并确保仿真接口的稳定搭建。文章详细解析了从单轴到多轴协同转向的配置方法,并提供了提升MPC路径跟踪精度的实战技巧与调试经验。

weixin_29035147的博客 383

历年安徽省省赛AHOI初中组考点分类汇总考点分类汇总

持续更新中.....

weixin_42358969的博客 822

Kotlin的魔能机甲——KtArmor(一)

前言 学习了Kotlin有一段时间了, 每次写项目/Demo的时候, 总是用到网络请求、MVP、MVVM、常用工具类、通用自定义View, 索性把这些整合到一起, 搭成一个Android的脚手架——KtArmor. 什么是KtArmor ? KtArmor 寓意着 为Android 赋予战斗装甲, 方便开发者快速进行Android 开发。节约开发者开发时间。为了满足开发者需求, 我整合了两个分支,...

HyZhan的博客 345

三菱FX5U系列PLC与汇川IT6000系列触摸屏进行MODBUS TCP通信的具体方法

三菱FX5U系列PLC与汇川IT6000系列触摸屏进行MODBUS TCP通信的具体方法

Robot_PLC_HMI_Automation 6536

Kotlin 类

Kotlin 类及其属性、方法、构造函数、伴生对象。

Chanwing Chow的博客 1240

【技能】伪真openclaw主动式智能体—告别‘巨婴’AI工具人:体验主动智能体的魅力

摘要: 传统AI常因被动执行、缺乏闭环而令人抓狂。Proactivity主动执行能力将AI从"指令跟随者"升级为"主动合伙人",具备预判需求、自动推进、断聊恢复、问题自解等能力。其核心原理在于建立AI专属工作体系(持久化内存、动态任务层、临时缓存层、归档复盘层),通过7步闭环(感知触发→状态恢复→边界校验→方案探索→动作决策→执行落地→状态留存)确保安全高效。

海兰 226

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

Kotlin中类的可见性

Kotlin 的final默认设计提高了代码的安全性、可维护性和封装性,适合编写稳定的大型项目代码。虽然牺牲了一定的灵活性,但有助于防止滥用继承,提高代码质量。Java:类和方法默认是public和non-final的,这意味着它们可以被继承和重写,除非显式声明为final。// 可以被子类重写@Override// 重写父类方法Kotlin:类和方法默认是final,必须使用open关键字显式声明,才能允许继承和重写。// 允许子类重写// 重写父类方法更安全的继承机制。

Junes inh 的技术专栏 1457

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Kotlin 类基础

kotlin是OOP模式的语言,其中的类是对事物的特征、逻辑的综合抽象,用关键词class声明一个类。包含class name, class header, class body。 class A {} class Empty 类的基本结构:构造函数,属性,方法 构造函数 构造函数是实例化一个类时调用的api,它可以接收参数来控制对象的特征与逻辑 构造函数可以用关键词constructor声明 kotlin的类有两种构造函数,主构造函数、次构造函数 主构造函数是class header的一部

ljjliujunjie123的博客 4408

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Kotlin 类和对象

本文全面介绍了Kotlin中的类和对象,重点讲解了其简洁语法和核心特性。主要内容包括:1)类声明与实例化,展示主构造函数和初始化块的使用;2)数据类的自动生成方法;3)单例和伴生对象的实现方式;4)继承与接口的应用;5)空安全特性。文章还提供了学生管理系统和Android开发两个实践示例,帮助读者理解Kotlin面向对象编程的实际应用。2025年Kotlin 2.0在类初始化性能上的优化也作了说明。

m0_57545130的博客 825

kotlin之的类的继承

kotlin之的类的继承前言kotlin类默认是不继承的kotlin实现类的继承 前言 在Java中类的继承默认是继承父类的方法和参数的,但是在kotlin中默认是不继承的,那么我们接下来来验证。 kotlin类默认是不继承的 首先我们定义一个BirdOne 的类 class BirdOne { var weight: Int = 10 fun fly() { ...

笨鸟不会飞 1226

【深入kotlin】- 类

类 Kotlin 中定义类有些地方不同于 java。 不需要 public 一个类默认就是 public 的,所以不用显示地声明一个类为 public。 不需要花括号 如果一个类是空实现,可以不需要 {} class MyClass 主构造方法 Kotlin 规定每个类允许有一个主构造方法和多个次要构造方法。 主构造方法是类名的一部分 主构造方法定义类名之后,用 constructor 关键字声明: class MyClass contructor(username: String){ ... } 这

kmyhy的专栏 2818

Kotlin中的类

以上就是 Kotlin 中的主要类类型。如果您还有其他关于 Kotlin 或其他 Android 相关的问题,欢迎随时提问。constructor 里的参数列表是首先被执行的,紧接着是 init 块和属性初始化器,最后是次构造函数的函数体。以下是两种生成的例子, Kotlin对下划线命名有警告, 所以自己不会生成下划线的名字, 使用注解的时候需要第三方库。通过伴生类实现单例模式, 每个类伴生类只允许一个, 伴生类的名字可有可无。2种静态类, 一种伴生类, 一种独立类。通过独立类实现工具类。

有速度的空气的博客 1510

Kotlin中类的继承

在 Kotlin 中所有类都有一个Anyequals()hashCode()与toString()。因此,为所有 Kotlin 类都定义了这些方法。默认情况下,Kotlin 类是最终(final)的——它们不能被继承。要使一个类可继承,请用open如果派生类有一个主构造函数,其基类可以(并且必须)根据其参数在该主构造函数中初始化。如果派生类没有主构造函数,那么每个次构造函数必须使用super关键字初始化其基类型,或委托给另一个做到这点的构造函数。

https://github.com/Mac-Zhu 893

【Kotlin 初学者】类和对象

Kotlin允许你不使用临时变量赋值,而是直接用一个定义同时指定参数和类属性,这种方式定义类属性,可以减少重复代码。这里我们对name进行了改造,直接在主构造函数里面定义属性,而不是通过临时变量进行赋值。次构造器我们可以定义多个次构造函数来配置不同的参数组合。同时,可以使用次构造函数,定义初始化代码逻辑。在同一个类中代理另一个构造函数使用this 关键字实践init {name今年已经name 今年已经name今年已经age 岁了”)//次构造器。

2401_84048586的博客 1017
上一篇: 性能优化相关
下一篇: Android吸顶效果,并有着ViewPager左右切换
叔怀
博客等级 码龄10年 127粉丝 151原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址