如何创建包级功能? [英] How to create package-level functions?

查看:51
本文介绍了如何创建包级功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读《科特林参考指南》 ,其中一部分说:

I was reading the Kotlin Reference Guide and one part said:

在Kotlin中,与Java或C#不同,类没有静态方法.在大多数情况下,建议您改用包级功能.

In Kotlin, unlike Java or C#, classes do not have static methods. In most cases, it’s recommended to simply use package-level functions instead.

如何创建包级功能?

推荐答案

从参考文献中:

源文件的所有内容(例如类和函数)都包含在声明的包中.

All the contents (such as classes and functions) of the source file are contained by the package declared.

因此只需创建一个像这样的源文件即可:

So simply by creating a source file like so:

package my.pkg

fun f0()=0
fun f1()=1

我们可以声明对my.pkg包直接可见的名为f0f1的函数.然后可以将这些函数导入并类似于类使用:

We can declare functions named f0 and f1 directly visible to the my.pkg package. These functions may then be imported and used similarly to classes:

import my.pkg.f0
import my.pkg.f1

或者,使用*语法:

import my.pkg.*

这篇关于如何创建包级功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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