关于实现scala的selftype的问题。

来源:8-7 案例:模拟 Self Type

weixin_慕斯卡5214421

2024-10-03

我感觉benny老师是为了引出scala的语法特性,扩展同学们的思路,所以才有上述解决方案。其实有一种更简洁的解决方案,也就是递归泛型,用这个思路去解决selftype问题,会引申出java对于递归泛型实现的一些问题。

贴代码

typealias OnConfirm = () -> Unit
typealias OnCancel = () -> Unit

private val EmptyFunction = {}

open class Notification(
    val title: String,
    val content: String
)

class ConfirmNotification(
    title: String,
    content: String,
    val onConfirm: OnConfirm,
    val onCancel: OnCancel
) : Notification(title, content)



open class NotificationBuilder< T : NotificationBuilder<T>> {
    protected var title: String = ""
    protected var content: String = ""

    fun title(title: String): T {
        this.title = title
        return this as T
    }

    fun content(content: String): T {
        this.content = content
        return this as T
    }

    open fun build() = Notification(this.title, this.content)
}

class ConfirmNotificationBuilder : NotificationBuilder<ConfirmNotificationBuilder>() {
    private var onConfirm: OnConfirm = EmptyFunction
    private var onCancel: OnCancel = EmptyFunction

    fun onConfirm(onConfirm: OnConfirm): ConfirmNotificationBuilder {
        this.onConfirm = onConfirm
        return this
    }

    fun onCancel(onCancel: OnCancel): ConfirmNotificationBuilder {
        this.onCancel = onCancel
        return this
    }

    override fun build() = ConfirmNotification(title, content, onConfirm, onCancel)
}

fun main() {
    ConfirmNotificationBuilder()
        .title("Hello")
        .onCancel {
            println("onCancel")
        }.content("World")
        .onConfirm {
            println("onConfirmed")
        }
        .build()
        .onConfirm()
}

现在问题来了,在java里,open class NotificationBuilder<T : NotificationBuilder>,这样的写法,能编译通过吗,而且认知上理解成T表示NotificationBuilder的本身和子类,更好理解,但是并不严谨。这里突出了NotificationBuilder和NotificationBuilder<T>的类型区别。

写回答

2回答

bennyhuo

2024-10-03

能理解到这一节核心思想,还能举一反三,同学的基础还是非常扎实的。👍🏻
1
0

bennyhuo

2024-10-03

看着代码量差不多,这样写其实理解难度会更大一些,也有类型强转。Java泛型可以不写泛型参数,盲猜应该可以,能不能编译可以试试看
1
3
weixin_慕斯卡5214421
回复
bennyhuo
回复 bennyhuo:wow
2024-10-08
共3条回复

学会Kotlin 突破开发语言瓶颈

如果有一门语言可以取代Java,那么它一定是Kotlin。

1760 学习 · 481 问题

查看课程