Code Monkey home page Code Monkey logo

kotlin-by-example's Introduction

Kotlin by Example

official JetBrains project

This is sources of Kotlin Examples.

How to make example

Create markdown file in examples folder.

# Header

Lorem ipsum dolor sit `amet`, consectetur adipisicing elit. Aspernatur, molestias, velit?

``​`run-kotlin
fun main(args: Array<String>) {
    println("Hello from template")
}
``​`

1. Epsum `factorial` non deposit quid pro quo hic escorol.
2. Souvlaki ignitus carborundum e pluribus unum.
3. Lorem ipsum dolor `sit` amet, consectetur adipisicing elit. Dicta ipsa ipsam odio officiis repellat suscipit unde vel voluptatibus. Dolorum esse eum fugit nihil provident quae quaerat quidem reiciendis, repudiandae ullam.
4. Quote meon an `estimate` et non interruptus stadium.
5. Quote meon an `estimate`


| Tables        | Are           | Cool  |
| ------------- |:-------------:| -----:|
| col 3 is      | right-aligned | 10000 |
| col 2 is      | centered      |   100 |
| zebra stripes | are neat      |    11 |

### Links

See more information in our [website](https://kotlinlang.org/)

Render as:

screen shot 2018-08-17 at 2 48 04 pm

How to use different attributes on runnable examples see Kotlin Playground documentation.

Guidelines

  1. Try and keep text to a minimum. Remember, this site is not trying to replace documentation nor necessarily describe all edge cases or dive into details. Rule of thumb should be a single paragraph introducing the example. Rest should be line annotations.
  2. Use 4 spaces for tabs.
  3. Make sure examples compile and also have some output when they run.

How to contribute

  1. Fork & clone our repository.
  2. Create new chapter with examples or add new example to existing chapter.
    1. Create chapter folder in examples folder.
    2. Create description.md file in your chapter and set a header — it's a chapter name!
    3. Create examples files.

Path to your example will be https://host/byExample/chapter/myExample1

Have a nice Kotlin!

kotlin-by-example's People

Contributors

aakashadesara avatar abhilashmandaliya avatar alexanderprendota avatar arseniyx avatar b1ggdave avatar chapeupreto avatar d3nn7 avatar dinomite avatar hakimrie avatar hhariri avatar homoefficio avatar jaredsburrows avatar jhult avatar kisenka avatar mariomac avatar martin-schulte avatar mranney-dd avatar npakudin avatar orderbynull avatar ossner avatar p7nov avatar pauleveritt avatar petersommerhoff avatar satamas avatar sebastianaigner avatar tatsuyafujisaki avatar thomaskalmar avatar vmishenev avatar wrherbert avatar zamulla avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kotlin-by-example's Issues

Add explanation that read-only variable (val) can refer to mutable object (e.g. List)

In the section Introduction under subsection Variables it would be very helpful if you showed an example where read-only variable refers to mutable object such as list with an explanation that variable itself is immutable, but object it refers to is mutable.

Because later in the subsection Generics there is this code:

class MutableStack<E>(vararg items: E) {

  private val elements = items.toMutableList()

  fun push(element: E) = elements.add(element)

  ...
}

This part was very unclear to me, it didn't quite get how can you add items to variable elements if the variable is immutable. Until I read at this source the following:

Also, while the read-only variable may not be reassigned while it is in scope, it can still refer to an object which is in itself mutable (such as a list).

That's why I think it would be very useful if you added explanation about immutable variables referring to mutable objects in the section Variables.

Dark Theme

I was reading the examples in the page and I noticed there's now way to change the theme of the page, having it would be pretty sweet and give eyes a break :P Maybe i'm being to dramatic but is there a way to get this implemented ?.

Possible typo in datatypes

https://play.kotlinlang.org/byExample/01_introduction/06_Generics

fun <E> mutableStackOf(vararg elements: E) = MutableStack(*elements)

fun main() {
  val stack = mutableStackOf(0.62, 3.14, 2.7)
  println(stack)
}

```Note that the compiler can infer the generic type from the parameters of mutableStackOf so that you don't have to write mutableStackOf<**Int**>(...).

-> shouldn't that be mutableStackOf<**Float**>(...) in this scenario?

HTML Builder example produces deprecation warning and is not aligned with Type Safe Builders reference doc

Running the HTML Builder example code in the https://play.kotlinlang.org/byExample/09_Kotlin_JS/06_HtmlBuilder page produces the expected result while displaying deprecation warnings next to several lines (please refer to the screenshot below).

kotlin example warnings

Attempt to run the code in Kotlin Playground fails with errors (please refer to the screenshot below).

kotlin playground errors

The Type Sage Builders reference doc mentioned at the bottom of the page contains a different implementation that [after minor adaptations] runs successfully in Kotlin Playground.

It seems beneficial to align HTML Builder example with with Type Safe Builders reference doc and make it executable in Kotlin Playground.

Adding user-friendly examples for getting started with K/N

Kotlin native is not the most beginner friendly tool out there at the moment. Maybe a suggestion for chapter 10 can be focused on some examples with full projects (Including buildscripts, def files, etc)? Multiple files? Maybe that might be undoable, but I think we should try.

Examples can be for all three platforms (Mingw, MacOs, and Linux)?

We can also add some examples for WebAssembly, and Swift porting?
This can be a great way for people to learn how to use libraries and such with Kotlin Native, and such a project allows us to cover many different kinds of projects.

Of course, we don't have to focus on the building part of things, we can also focus on creating examples for memory management, etc.

Sandbox mode broken

Am I doing something wrong?
Examples in docs and default code in sandbox at https://play.kotlinlang.org/ throw an exception

Exception in thread "main" java.io.FileNotFoundException: /var/task/tmp/5123f1e03e204326b652cc46776a48ba/executor.policy (No such file or directory)
at java.io.FileOutputStream.open0 (FileOutputStream.java:-2)
at java.io.FileOutputStream.open (FileOutputStream.java:270)
at java.io.FileOutputStream. (FileOutputStream.java:213)

Target platform: JVM
Running on kotlin v.1.5.31

Found this accidentally when trying to execute basic code in playground

Example in 09_Kotlin_JS/05_Canvas produces errors

This code

CanvasState(canvas).apply {
    addShape(Kotlin)
    addShape(Creature(size * 0.25, this))
    addShape(Creature(size * 0.75, this))
}

returns the following errors when run on the page:

Using 'jq(Element): JQuery' is an error. Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead.
Using 'jq(Element): JQuery' is an error. Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead.
Using 'jq(Element): JQuery' is an error. Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead.
Using 'jq(Element): JQuery' is an error. Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead.
Using 'MouseEvent' is an error. Use declarations from 'https://bintray.com/kotlin/js-externals/kotlin-js-jquery' package instead.

Tested on

  • Chrome Version 85.0.4183.121 (Official Build) (64-bit), on Windows 7 x64 pro
  • Microsoft Edge Version 85.0.564.63 (Official build) (64-bit), same platform

Replace reference numbers with inline comments

Background

I'm brand new to Kotlin and working through Kotlin by Example. I've noticed that each topic is organised into a structure similar to the following:

package org.kotlinlang.play         // 1

fun main() {                        // 2
    println("Hello, World!")        // 3
}
  1. Kotlin code is usually defined in packages. Package specification is optional: If you don't specify a package in a source file, its content goes to the default package.
  2. An entry point to a Kotlin application is the main function. In Kotlin 1.3, you can declare main without any parameters. The return type is not specified, which means that the function returns nothing.
  3. println writes a line to the standard output. It is imported implicitly. Also note that semicolons are optional.

Problem

Personally, I find this difficult to follow. For each line of code, I need to:

  1. Read the line of code
  2. Memorise the reference number at the end of the line
  3. Skip down the page to the reference notes
  4. Find the reference note with the memorised reference number
  5. Read the reference note
  6. Skip back up the page to the code
  7. Find the line of code I was last at

By the time I finish the topic, I have skipped up and down the page several times.

Solution

Inline the reference notes into the code:

// Kotlin code is usually defined in packages.
// Package specification is optional: If you don't specify a package in a source file,
// its content goes to the default package.
package org.kotlinlang.play

// An entry point to a Kotlin application is the main function.
// In Kotlin 1.3, you can declare main without any parameters.
// The return type is not specified, which means that the function returns nothing.
fun main() {
    // println() writes a line to the standard output.
    // It is imported implicitly. Also note that semicolons are optional.
    println("Hello, World!")
}

Benefits

Now, instead of having to keep skipping down and up the page, I can just follow it from top to bottom. So for each line of code, I need to:

  1. Read the comment
  2. Read the line of code

I find this significantly easier to follow than the way it's currently done.

Alternative solution

If you don't like the look of detailed notes inside code comments, then you could interleave the notes with the code:

Kotlin code is usually defined in packages. Package specification is optional: If you don't specify a package in a source file, its content goes to the default package.

package org.kotlinlang.play

An entry point to a Kotlin application is the main function. In Kotlin 1.3, you can declare main without any parameters. The return type is not specified, which means that the function returns nothing.

fun main() {

println writes a line to the standard output. It is imported implicitly. Also note that semicolons are optional.

    println("Hello, World!")
}

This way is a bit nicer to read, but now it's hard to copy and run the full code block since it's split up, so I'm not sure if it's worth it.

Pull request

I'm happy to make the changes myself and submit a pull request.

GitHub language detection

In my opinion, projects like this should be detected and recognized with the programming language they are based on, and not with the file extension used (.md). So, in my opinion, should be added a .gitattributes to force GitHub to consider it a Kotlin project.

A generic .gitattributes could be:
*.* linguist-language=Kotlin

My two cents

The documentation for Null Safety doesn't work this way.

Null Safety
In an effort to rid the world of NullPointerException, variable types in Kotlin don't allow the assignment of null. If you need a variable that can be null, declare it nullable by adding ? at the end of its type.

fun main() {
//sampleStart
var neverNull: String = "This can't be null" // 1

neverNull = null                                        // 2

var nullable: String? = "You can keep a null here"      // 3

nullable = null                                         // 4

var inferredNonNull = "The compiler assumes non-null"   // 5

inferredNonNull = null                                  // 6

fun strLength(notNull: String): Int {                   // 7
    return notNull.length
}

It should be this in documentation :
println(strLength(neverNull)); // 8
println(strLength(nullable)); // 9

instead of this:
strLength(neverNull) // 8
strLength(nullable) // 9
//sampleEnd
}

i have already created the pull request for this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.