Kotlin语法:使用类名而不是伴随对象名的区别

时间:2018-11-06 04:22:43

标签: kotlin ktor

看看这段代码,该代码模仿features应用程序中如何安装Ktor

(
    SELECT
        0 AS marker
        pAll.ProductID,
        SUM(CASE WHEN oAll.OrderDate BETWEEN '1996-10-01' AND '1996-10-31'
                 THEN odAll.Quantity * pAll.Price ELSE 0 END) -
        SUM(CASE WHEN oAll.OrderDate BETWEEN '1996-09-01' AND '1996-09-30'
                 THEN odAll.Quantity * pAll.Price ELSE 0 END) AS sales_diff
    FROM OrderDetails odAll 
    INNER JOIN Orders oAll 
        ON oAll.OrderID = odAll.OrderID
    INNER JOIN Products pAll
        ON odAll.ProductID =  pAll.ProductID
    GROUP BY pAll.ProductID
    ORDER BY sales DESC
    LIMIT 3
)
UNION ALL
(
    SELECT
        1
        pAll.ProductID,
        SUM(CASE WHEN oAll.OrderDate BETWEEN '1996-10-01' AND '1996-10-31'
                 THEN odAll.Quantity * pAll.Price ELSE 0 END) -
        SUM(CASE WHEN oAll.OrderDate BETWEEN '1996-09-01' AND '1996-09-30'
                 THEN odAll.Quantity * pAll.Price ELSE 0 END) AS sales_diff
    FROM OrderDetails odAll 
    INNER JOIN Orders oAll 
        ON oAll.OrderID = odAll.OrderID
    INNER JOIN Products pAll
        ON odAll.ProductID =  pAll.ProductID
    GROUP BY pAll.ProductID
    ORDER BY sales
    LIMIT 3
)
ORDER BY
    marker,
    CASE WHEN marker = 0 THEN sales_diff ELSE -1*sales_diff END DESC;

上面的代码段对我来说没有意义的是这一行fun main(args: Array<String>) { val app = App() app.installFeature(Authentication) } interface AppFeature { fun install() } class Authentication { companion object Feature : AppFeature { override fun install() = println("Authentication Installed") } } class App { fun installFeature(appFeature: AppFeature) { println("Installing appFeature `${appFeature::class.simpleName}`") appFeature.install() } }

任何人都可以向我解释为什么使用app.installFeature(Authentication)名称而不是class名称就像更明显的方法companion object

1 个答案:

答案 0 :(得分:2)

documentation中所述:

  

只需使用类名作为限定符即可调用伴随对象的成员

同样,您可以直接将Authentication用作AppFeature