Kotlin从入门到放弃Kotlin学习日记Kotlin

{Kotlin学习日记}Day20 Koan第四关

2017-07-27  本文已影响65人  William李梓峰

大家好,我是William。今天是Koan第四关,Default arguments,默认参数。

https://try.kotlinlang.org/#/Kotlin%20Koans/Introduction/Default%20arguments/Task.kt
上面是闯关链接。

Introduction

Default arguments

There are several overloads of 'foo()' in Java:

public String foo(String name, int number, boolean toUpperCase) {
    return (toUpperCase ? name.toUpperCase() : name) + number;
}

public String foo(String name, int number) { 
    return foo(name, number, false);
}

public String foo(String name, boolean toUpperCase) { 
    return foo(name, 42, toUpperCase);
}

public String foo(String name) { 
    return foo(name, 42);
}

All these Java overloads can be replaced with one function in Kotlin. Change the declaration of the function foo in a way that makes the code using foo compile. Use default and named arguments.
译:
不翻译了,看不懂题目就放弃治疗吧

解:
本题还是延续昨天函数的特性。直接让你设计一个函数秒杀上面四个Java重载函数,昨天我特意就说了,Kotlin不需要重载函数,就像JavaScript或Python一样。

答:
注意答案中的if-else用法。

fun foo(name: String, number: Int = 42, toUpperCase: Boolean = false) =
        (if (toUpperCase) name.toUpperCase() else name) + number

fun useFoo() = listOf(
        foo("a"),
        foo("b", number = 1),
        foo("c", toUpperCase = true),
        foo(name = "d", number = 2, toUpperCase = true)
)

小结

第四关有点无聊,今天就到这。

号外

最近想写写以项目为单位的开发日记,从零开始搭建项目,遇到不懂就立刻开小专题学习,过程中将遇到我是如何用最小成本确定需求设计开发构建部署测试发布监控。技术栈直接用当下最新的最主流的来搞。前端是JavaScript的Vue家族+NodeJS,后端是Java的Pivotal家族+Hadoop家族,数据分析用R语言+Python,负载均衡暂定Nginx,DB要根据场景来定,操作系统是CentOS7,容器环境考虑是先Docker后k8s最后转Pivotal Cloud Foundry有空再来OpenStack,先OS层面部署后容器层面部署,版本管理用Git,代码仓库是Github,CI\CD用Jenkins,移动端用Kotlin,域名是直接用Github提供的,不考虑用任何付费第三方基础设施(文件系统、消息推送、对象存储等),尝试走一遍完整的开发流程,然后转行去中关村卖烧饼,顺便做做路演讲讲故事拉拉投资,跟互联网大佬谈笑风生。

上一篇下一篇

猜你喜欢

热点阅读