Kotlin-使扩展功能可在整个项目中访问 [英] Kotlin - Make extension function accessible in whole project

查看:70
本文介绍了Kotlin-使扩展功能可在整个项目中访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在课堂上有这个扩展功能:

I have this extension function in a class:

fun Double.round2() : Double {
   return Math.round((this) * 100.0) / 100.0
}

我想在另一个类中重用此函数,而无需重复代码.我该怎么做?谢谢.

I want to reuse this function in another class without the need to duplicate the code. How can I do it? Thank you.

推荐答案

您的函数应在顶层定义.借助import语句,可以在同一软件包的任何位置以及其他软件包的任何位置自动看到该变量.

Your function should be defined at the top level. It will be automatically visible anywhere from the same package, and from other packages with the help of an import statement.

这篇关于Kotlin-使扩展功能可在整个项目中访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆