第十期的一个问题
cooperkong opened this issue · comments
首先感谢视频制作,对刚学Kotlin来说真是极好的。希望能继续下去,期待Kotlin和Android的视频。
第十期讲单例中的LazyNotThreadSafe类里,用到了
fun getInstance() = {
if(instance2 == null)
instance2 = LazyNotThreadSafe()
instance2
}
而为什么不是传统function写法呢
fun getInstance() : LazyNotThreadSafe{
if(instance2 == null)
instance2 = LazyNotThreadSafe()
return instance2
}
//报错,Platform declaration clash: The following declarations have the same JVM signature (getInstance()Ldemo/singleton/LazyNotThreadSafe;):
可是这两种写法方法名是一样的啊,小白求解
非常感谢哈,这是个错误,当时没太注意到,我更新一下代码。getInstance 跟前面的 instance 冲突了,这里讲到的实际上是同一种原理的两种实现,所以冲突是正常的。
回头我写篇勘误放上来吧。
我觉得可能我没描述清楚,
两种实现是没问题,但是假如by lazy和传统返回值那个function 一起存在就会报错,但是可以和那个anonymous function 一起存在,这个不知道是为什么
fun getInstance() = {
if(instance2 == null)
instance2 = LazyNotThreadSafe()
instance2
}
这种写法是错误的其实,我当时没太注意,它返回的是一个Lambda表达式,这样函数签名就不一样了,所以ide没有提示冲突。
注意到签名有个 var instance: ... 这个会生成一个 getInstance 的getter 方法。
这个。。是我的问题,我把视频和代码修改一下就好了。当时重点没有放到这个上面,毕竟在 Kotlin 里面咱们不需要直译 Java 的单例,有些疏忽了。
楼主很细心,多谢你发现这个问题!
@enbandari decompile 看了下,用=那样做生成的是 public final Function0 getInstance() { return (Function0)null.INSTANCE; }
和 var instance 生成的getInstance 共存在decompile完后的文件里,这是咋回事?
嗯,返回值不同
刚刚我已经更新了视频和代码~~
话说你都不睡觉么。。还是有时差。。5点多回复。。 @cooperkong
@enbandari 哈哈,在澳村有时差:)你也是够早起床的啊,很负责,👍
哈哈,睡得早起得早
有问题可以持续发邮件给我讨论哈,这个我就关掉啦