【问题标题】:Function definition in parameter of class extension?类扩展参数中的函数定义?
【发布时间】:2017-11-03 19:07:14
【问题描述】:

this part of Play Framework documentation,我找到了下面这行代码:

object Authenticated extends AuthenticatedBuilder(req => getUserFromRequest(req))

让我困惑的部分是eq => getUserFromRequest(req))。为什么超类的参数中有函数定义?难道它不应该只保存应该由子类继承的超类的参数吗?

【问题讨论】:

    标签: scala inheritance subclass


    【解决方案1】:

    在 Scala 中,函数是一等元素,这意味着它们可以作为参数传递并作为函数结果返回。

    source file 中我们看到AuthenticatedBuilder 需要两个构造函数参数,它们都是函数。

    class AuthenticatedBuilder[U](userinfo       : RequestHeader => Option[U]
                                 ,onUnauthorized : RequestHeader => Result =
                       _ => Unauthorized(views.html.defaultpages.unauthorized())
                                 ) extends ActionBuilder[...] { ...
    

    在您引用的示例中,仅提供了一个参数,因为第二个参数具有默认值。

    【讨论】:

    • 知道了。我错误地认为你不能给你继承的类提供任何具体的参数,只有参数。也就是说,我认为这不合法:class Person (name: String, age: Int); object Bobby extends Person("Bobby", 12).
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 2023-01-23
    相关资源
    最近更新 更多