• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Kotlin Programming Language

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):


开源软件地址(OpenSource Url):


开源编程语言(OpenSource Language):


开源软件介绍(OpenSource Introduction):

Why Kotlin

Modern, concise and safe programming language

Easy to pick up, so you can create powerful applications immediately.

  • Concise

    data class Employee(
       val name: String,
       val email: String,
       val company: String
    ) // + automatically generated equals(), hashCode(), toString(), and copy()
    
    object MyCompany {                                // A singleton
       const val name: String = "MyCompany"
    }
    
    fun main() {                                      // Function at the top level
       val employee = Employee("Alice",               // No `new` keyword
          "[email protected]", MyCompany.name)
       println(employee)
    }
    
    
  • Safe

    fun reply(condition: Boolean): String? =          // Nullability is part of Kotlin’s type system
       if (condition) "I'm fine" else null
    
    fun error(): Nothing =                            // Always throw an exception
       throw IllegalStateException("Shouldn't be here")
    
    fun main() {
       val condition = true                        // Try replacing `true` with `false` and run the sample!
       val message = reply(condition)              // The result is nullable
       // println(message.uppercase())             // This line doesn't compile
       println(message?.replace("fine", "okay"))   // Access a nullable value in a safe manner
       if (message != null) {                      // If you check that the type is right,
          println(message.uppercase())             // the compiler will smart-cast it for you
       }
    
       val nonNull: String =                             // If the null-case throws an error,
       reply(condition = true) ?: error()             // Kotlin can infer that the result is non-null
       println(nonNull)
    }
    
  • Expressive

    fun main() {
    //sampleStart
       val map = mapOf(1 to "one", 2 to "two")
       for ((k, v) in map) {                            // Traverse a map or a list of pairs
           println("$k -> $v")
       }
    
       fun obtainKnowledge() = Pair("The Answer", 42)   // Single-expression functions
    
       val (description, answer) = obtainKnowledge()    // Destructure into a pair of two variables
       println("$description: $answer")
        
       getText()?.let {                                 // Apply an action to a nullable expression
          sendEmailTo("[email protected]", it)          // if it’s not null 
       }
    
       createEmptyWindow()
          .apply {                                    // Configure properties of an object
             width = 300
             height = 200
             isVisible = true
          }.also { w ->                               // Perform an additional operation on a call chain
             showWindow(w)
          }
    
       val fixedIssue = issueById["13456"]
           ?.takeIf { it.status == Status.FIXED }       // Use the value only if the condition is true
       println(fixedIssue)
    //sampleEnd
    }
    
    data class Window(var width: Int, var height: Int, var isVisible: Boolean)
    
    fun createEmptyWindow() = Window(0, 0, false)
    
    fun showWindow(window: Window) {
       println("Showing $window")
    }
    
    fun getText(): String? = "Hi! You've won the lottery! Pay the attached bill to get the prize."
    fun sendEmailTo(to: String, message: String) {
       println("Sending email to $to: \n$message")
    }
    
    enum class Status { OPEN, FIXED, IN_PROGRESS }
    data class Issue(val status: Status)
    val issueById = mutableMapOf(
       "13456" to Issue(Status.FIXED)
    )
    
  • Interoperable

    // Use any existing JVM library or framework
    // Call Kotlin code from Java without an issue
    
    @SpringBootApplication
    class DemoApplication
    
    fun main(args: Array<String>) {
       runApplication<DemoApplication>(*args)
    }
    
    @RestController
    class MessageResource {
       @GetMapping
       fun index(): List<Message> = listOf(
          Message("1", "Hello!"),
          Message("2", "Bonjour!"),
          Message("3", "Privet!"),
       )
    }
    
    data class Message(val id: String?, val text: String)
    
    // Write Kotlin code, compile it to JavaScript, and run it in the browser
    // Use existing JavaScript APIs and libraries
    
    import kotlinx.browser.window
    
    fun main() {
       val body = window.document.body
    
       body?.innerHTML += "<b>Hello, <i>Kotlin</i></b>"
    
       window.setInterval({
          body?.innerHTML += "!"
       }, 1000)
    }
    
    // Use Kotlin wrappers to build applications with JavaScript frameworks such as React
    
    import react.*
    import react.dom.*
    import kotlinx.html.js.onClickFunction
    
    val counter = functionalComponent<Props> {
       val (count, setCount) = useState(0)
       button {
          attrs.onClickFunction = { setCount(count + 1) }
          +count.toString()
       }
    }
    
  • Multiplatform

    // Common
    // Declare signatures to use them in the common code
    // Provide platform-specific implementations in the platform modules
    expect fun randomUUID(): String
    
    expect class PlatformSocket(
           url: String
    ) {
        fun openSocket(listener: PlatformSocketListener)
        fun closeSocket(code: Int, reason: String)
        fun sendMessage(msg: String)
    }
    
    interface PlatformSocketListener {
        fun onOpen()
        fun onFailure(t: Throwable)
        fun onMessage(msg: String)
        fun onClosing(code: Int, reason: String)
    }
    
    import java.util.*
    
    actual fun randomUUID() = UUID.randomUUID().toString()
    
    actual class PlatformSocket actual constructor(url: String) {
       // Use okhttp3 in implementation
    }
    
    // iOS
    import platform.Foundation.NSUUID
    
    actual fun randomUUID(): String = NSUUID().UUIDString()
    
    actual class PlatformSocket actual constructor(url: String) {
       // Use platform.Foundation in implementation
    }
    
    
    // JS
    // Use the `uuid` package from npm as dependency
    actual fun randomUUID(): String = uuidv4() 
    
    actual class PlatformSocket actual constructor(url: String) {
       // Implementation on top of WebSockets
    }
    
Get started →

A productive way to write server‑side applications

Compatible with the Java ecosystem. Use your favorite JVM frameworks and libraries.

Learn more →

Cross-platform layer for native applications

Share application logic between web, mobile, and desktop platforms while keeping an experience native to users.

Save time and get the benefit of unlimited access to features specific to these platforms.

Mobile platforms Feature
Learn about Kotlin Multiplatform → Learn more →

Big, friendly and helpful
community

Kotlin has great support and many contributors in its fast-growing global community. Enjoy the benefits of a rich ecosystem with a wide range of community libraries. Help is never far away — consult extensive community resources or ask the Kotlin team directly.

Join the community →



鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap