使用默认参数的kotlin重载方法 [英] kotlin overload method with default parameter

查看:78
本文介绍了使用默认参数的kotlin重载方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,我得到了以下两种方法.

Here is the scenario, I got the below two methods.

fun foo(p1:Int,p2:String?=null)

fun foo(p1:Int,p2:Int=0)

如何使用 foo(1)引用特定的方法?

How do I refer to the specific method with foo(1)?

推荐答案

如果调用方只有一个参数,这是一个错误:

This is an error if the caller only has one parameter:

foo(1) // error

错误:(Y,X)Kotlin:重载分辨率不明确:

Error:(Y, X) Kotlin: Overload resolution ambiguity:

public fun foo(p1:Int,p2:Int = ...):在Mypackage中MyFile.kt文件中定义的单元

public fun foo(p1: Int, p2: Int = ...): Unit defined in mypackage in file MyFile.kt

公共乐趣foo(p1:Int,p2:String?= ...):在Mypackage中MyFile.kt文件中定义的单位

public fun foo(p1: Int, p2: String? = ...): Unit defined in mypackage in file MyFile.kt

因此,您必须以不同的方式命名它们,或提供另一个区分符(另一个参数),以便编译器知道选择哪个选项.它也无法想象选择默认值的第二个参数是什么.

So you have to name them differently or provide another differentiator (another parameter) so that the compiler knows which option to choose. It has no way to imagine what the second parameter might be to chose a default value either.

如果可以使逻辑工作(也许不是),您也可以将其组合为一个具有两个可选参数的功能.

You could also combine it into one function having both of the optional parameters present if you can make your logic work from that (maybe not).

或者仅用两个相关名称来命名它们,这些名称也描述了差异,例如某些虚构方法:

Or have them just named with two related names that also describes the difference, for example for some ficticious method:

calcValueFromInt(p1: Int, p2: Int = 0) { ... }
calcValueFromString(p1: Int, p2: String? = null) { ... } 

无论如何这都会提高可读性.

This improves readability anyway.

这篇关于使用默认参数的kotlin重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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