-
Notifications
You must be signed in to change notification settings - Fork 523
[FEATURE]修改kotlin扩展Any.contains函数名,以及其他类似的相关扩展函数 #1402
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
第二种解决方法不太合适,毕竟同一个文件里也可能在使用了fastjson2的contains的同时使用kotlin.text.contains,建议修改函数名。 |
您好, 感谢您指出不足之处. 在您们项目中可能是使用通配导入 |
感谢您的回复,祝项目越来越好 |
* refactor: remove conflicting functions (incompatible) #1402 * docs: update the comments of JSON.kt * refactor: remove the tests of JSONPathTest.kt
问题和需求描述
在一次debug过程中,我们团队发现一句必定正确的逻辑判断永远返回false,最终我们发现是fastjson2间接引起的问题.
1.起因
fastjson2
的kotlin扩展包为kotlin提供了许多扩展方法,如parseArray()
、parseObject()
、to<T>()
、into<T>()
、eval<T>()
等,去年我们使用kotlin + springboot的项目将fastjson包升级到了2.0,升级的原因之一就是新版提供了kotlin支持,同时,我们引入kotlin扩展包的初期体验到了极大的方便:但是,这些扩展函数的设计中,有少数几个扩展函数存在很大的问题。
拿我最开始的情况,举个例子:
kotlin.text包内String的
contains
函数是一个非常常用的函数,用于判断字符串的包含关系自从2.0.4以来,fastjson2提供了一个没有限制作用域和类型的扩展函数Any.contains
这个扩展函数经常会在调用String.contains(other)的时候被悄悄自动引入进来,导致一些非常隐含的报错,而且一旦引入,整个文件所有的contains都完了。

如下图所示,它的优先级甚至比kotlin.text默认的contains(charSequence)还高。
作为一个写kotlin各种平台(android/后台/multiplatform)代码,并且设计过kotlin框架的人,我认为这些函数存在以下问题:
Any
,如contains
,eval
,writeTo
等,很多类可能有自己的contains、eval、writeTo函数,在调用时很可能会调错请描述你建议的实现方案
像Any.toJSONString这种就不会引起歧义,可以考虑修改函数名
需要做的就是将有关的函数设置为废弃,修改函数名后重新发包(可以使用@deprecated + ReplaceWith)
我认为contains这个函数修改的优先级很高,其他名字中没有体现JSON的、加在Any上的扩展函数是一种很不负责任的起名方式,毕竟扩展函数会对整个项目所有的对象函数调用进行污染。
增加一个@RequiresOptIn(level = RequiresOptIn.Level.ERROR, message = "xxx")注解,在调用此类函数时需要额外加入一个Opt,及早发现调用了错误的函数,防止这一类bug的发生。
例:
实际调用时:

The text was updated successfully, but these errors were encountered: