
Swift is like Kotlin - mastazi
http://nilhcem.com/swift-is-like-kotlin/
======
jnbiche
Kotlin lacks the ability to do true functional programming that Swift has.
Swift has pattern matching, recursive data structures (edit: specifically ADTs
with enums or case classes is what I was thinking of here, should have written
algebraic data types), tail call optimization, even some form of type classes,
immutability (thanks @tmail21), and so on.

Kotlin does not have any of these (edit: this is now partly false, see below)

I'm sad that Google is supporting Kotlin and not Swift or Scala for Android,
since at least with the latter two, you can use functional programming.

Edit: Actually, I'm looking into Kotlin again, and it looks like it's greatly
expanded support for functional programming compared to a year or two ago. For
example, algebraic data types _can_ now be encoded in a similar manner to
Scala, and kind of pseudo-pattern matched using `when`. TCO is now supported.
There are lambdas, and support for closures. Destructuring assignment. But as
far as I can see, still no immutable values (just immutable references), and
no way to make extensible type classes, like in Scala and Swift.

I'm definitely going to take another look now. Last I checked a few years ago,
Kotlin had very limited support for functional programming.

~~~
pillowkusis
Maybe you haven't checked out Kotlin lately?

Kotlin has somewhat pattern matching:
[https://kotlinlang.org/docs/reference/control-
flow.html#when...](https://kotlinlang.org/docs/reference/control-
flow.html#when-expression)

Tail call optimization:
[https://kotlinlang.org/docs/reference/functions.html#tail-
re...](https://kotlinlang.org/docs/reference/functions.html#tail-recursive-
functions)

Type classes: [https://kotlinlang.org/docs/reference/sealed-
classes.html](https://kotlinlang.org/docs/reference/sealed-classes.html)

And I'm not sure what you mean by recursive data structures. Basically every C
style language I'm aware of can contain a reference to another instance of its
own type.

It's more java-y than Scala, but it's fundementally capable of a very FP
style.

~~~
Filligree
> Type classes: [https://kotlinlang.org/docs/reference/sealed-
> classes.html](https://kotlinlang.org/docs/reference/sealed-classes.html)

Those are not type-classes, at least not in the Haskell sense. They allow you
to avoid an else branch, yes, which is actually quite useful; but one basic
ability they're missing is the ability to define a new branch for a new
instance of the type defined by library users.

Just as an example. They're really not much like type-classes at all.

------
chc
I feel like you could about as well write an article about how Go or Scala or
TypeScript is like Kotlin. They all have some cases where they look similar or
have some similar constructs borrowed from other sightly-less-recent
languages. It doesn't seem like a very interesting or deep similarity.

If you want to compare them, going over the differences would be a lot more
illuminating.

~~~
ranit
I don't know it for a fact, but this seems a response to Steve Yegge's catchy
"Kotlin is better" (also on HN first page now).

~~~
krallja
In fact, it's linked from the Yegge post.

~~~
mastazi
OP here - Yes I posted the link after finding it in Yegge's post. I thought it
was interesting to see examples of the two languages side by side.

------
_31
Past the syntax similarities, both of these languages are intended
replacements for an 'old' language (Objective-C => Swift, Java => Kotlin) on a
dominant mobile platform, with interoperability as a major selling point
(requirement?). As a mobile dev (mainly iOS) this is awesome to see and
although I love me some Objective-C, working with swift has been a pleasure.
Now Java on the other hand... ( _shudders_ ). With Google making Kotlin an
official/first-class language and the syntax being so similar to swift I could
see myself spending more time working with Android.

~~~
piotrkubisa
I assume Google will try to replace Java with Dart, because they have recently
been focused on Flutter [1] [2] and Fuschia [2] development which are (mostly)
C++ and DartLang stack.

[1]: [https://flutter.io/](https://flutter.io/)

[2]: [https://github.com/flutter/](https://github.com/flutter/)

[3]: [https://github.com/fuchsia-mirror](https://github.com/fuchsia-mirror)

~~~
_pmf_
> I assume Google will try to replace Java with Dart

I would have expected this, but not after pushing Kotlin. Kotlin is shiny
enough to temporarily distract the typical developer from the daily struggles
with the abysmal Android API.

Kotlin and Java it will be for the next 10 years, for better or worse.

Dart is not very popular within Google itself, and Fuchsia is nothing more
than a paid hobby project[0].

[0] See
[https://www.reddit.com/r/programming/comments/6a026o/googles...](https://www.reddit.com/r/programming/comments/6a026o/googles_fuchsia_smartphone_os_dumps_linux_has_a/dhbjmvx/)
for a pretty damning review

~~~
tym0
> Dart is not very popular within Google itself

I was under the impression that pretty much all the frontend work at google
was compiled from Dart.

~~~
_pmf_
Only AdSense.

~~~
MR_HANDS
Isn't AdSense a pretty big deal within google?

~~~
JeremyBanks
Yes, the Ads organization is huge and has a large influence on front-end
development in general at Google.

------
Black-Plaid
It's strange that on the Kotlin side the author goes out of their way to show
'shorter' ways to do things that are also available in Swift but not
illustrated.

    
    
        let sorted = [1, 3, 6].sorted()
        let sum = [1, 3. 6].reduce(0, +)
    

as examples

~~~
agumonkey
while we're at it
[http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.34.16...](http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.34.1618)

~~~
throwaway7645
Why are you citing an FP comp Sci professor? I must've missed something

~~~
agumonkey
seeing reduce in swift made me think about the universality of fold, which is
the paper linked.

~~~
throwaway7645
Ah, was about to say that all goes back to lambda calculus by Church and could
be found in Lisp probably around ~1958.

~~~
agumonkey
Actually I think there's a relation with exponentials and integral calculus.
Or anything hyper-iteration related.

------
Unknoob
The article is missing the similarities between Swift Optionals and Kotlin
Nullables.

Swift code:

    
    
      var name: String?
    
      name? ///returns a safe value
      name! ///returns an unsafe value and throws an exception in case of a nil value
    
      if name != nil {
       ///Now we can use name! forcing unwrap because we know it's not nil
      }
    
      if let unwrapedName = name {
       /// Here we can use unwrapedName without forcing the unwrap
      }
    

The null checks are almost the same in Kotlin:
[https://kotlinlang.org/docs/reference/null-
safety.html](https://kotlinlang.org/docs/reference/null-safety.html)

~~~
jorgemf
kotlin make it a bit simpler, once you do name != null you can use it as it is
never null after than, there is not need to use let. It makes it more
readable.

------
NathanFlurry
One has structures, ARC, proper extensions, good protocols/interfaces,
flexible enums, and runs natively. The other one doesn't. I think I'll choose
the former.

~~~
coldtea
One has a top-notch IDE from a top-notch IDE vendor. The other has XCode.

Also, ARC aside, for the 3-4 items you mentioned, either Kotlin also also has
them, or has just as good alternatives. And none of those are life-changing.
ARC vs a good GC is just a different tradeoff (no cycle detection vs pauses,
etc).

I'm sure you can find some things where Swift is better at, and others where
Kotlin is. But not that many to proclare one or the other the definite winner,
and surely not a major one.

~~~
Tanegashima
Sure thing...

When will Jetbrain have a decent interface builder?

Decent instrumentation?

Decent documentation viewer?

Can you get an object graph with JetBrains?

Xcode isn't perfect, but it's way better than JetBrains.

Just because one has one feature that one doesn't have, doesn't mean that
Xcode beats JetBrain's IDE all day.

~~~
shadowmint
> Xcode isn't perfect, but it's way better than JetBrains.

O_o Are you kidding me?

People whinge all the time about jetbrains subscriptions, but I've literally
never spoken to someone who's actually used their products and think that the
alternative editors available (visual studio, xcode, etc) are actually better.

There are some features like UI designers that you can't do without, but it's
been a long time since I met anyone who actually _liked_ xcode.

~~~
wruza
I tried AppCode to write in objc on mac and it felt way less transparent and
smooth than Xcode. Idk if Xcode is missing some features, but all my real
issues probably exist in different planes. My Xcode inconvenience points are:
case-insensitive completion sometimes gets in my way, as it is with single
lettered variables; it is easy to break constraints for non-trivial xib. I can
live with both. What is it for you, in short?

~~~
coldtea
Unless very recently XCode also crashed like crazy. So there's that.

------
phkahler
I find it very annoying that Google and Apple are creating new languages to
solve similar problems and not worrying about cross platform. If you write for
Apple you've been told to use Objective-C and Swift. If you're on Android it's
Dart and now Kotlin. None of that stuff is used for Windows or Linux
development or even mobile on the other OS.

I'm not a fan of proliferation of "platforms" but when it goes beyond
libraries and into the language itself I consider that a very serious problem.

This is forcing developers to write apps twice, or use a 3rd party solution to
run on both OSes. Yep, they're refusal to work together and create standards
is allowing companies like Microsoft to have value by offering yet another
solution that works on both phones.

~~~
dannyr
Imagine having just one programming language where there is likely one
gatekeeper.

I doubt language innovation would happen with that setup.

~~~
BaronSamedi
Imagine having hundreds of languages with only trivial difference in syntax.
Consider the fragmentation and effort wasted on re-inventing the same low
level libraries again and again (here is the hundredth version of unit test
library). Sure, only language would be bad but so is too many.

~~~
dannyr
If a language has trivial difference from another language, I doubt it can
gain traction.

Can you cite an example?

~~~
oblio
A language doesn't gain traction cause of syntax or anything like that. It
gains traction because a platform developer promotes it.

C# and Java had what amounted to trivial differences, when they started.

Kotlin and Swift also aren't very far apart, both in terms of syntax and power
(in Blub power continuum terms).

There's very Computer Science-y reasons for these languages to exist as
separate languages, but they do cause of product differentiation and platform
lock-in efforts.

------
martijn_himself
Does anyone else think the Kotlin syntax for array literals is super ugly:

val shoppingList = arrayOf("catfish", "water", "tulips", "blue paint")

What is wrong with square bracket syntax? (rant over).

EDIT: I suppose it's consistent with other syntax e.g. listOf() etc.

~~~
masklinn
> Does anyone else think the Kotlin syntax for array literals is super ugly:

Well yeah, except it's really that Kotlin does not have array literals at all,
arrayOf is just a variable-arity function.

~~~
billyjobob
I guess they think they are cool for being able to provide this feature
through a library function rather than a language construct, but someone
should tell them they really need to add some syntactic sugar that
transparently invokes arrayOf while looking nicer.

~~~
mikeash
It's worth nothing that Swift literals are _mostly_ library constructs as
well. Any type conforming to ArrayLiteralConvertible can be instantiated using
[...] syntax, for example. All other literal types (integers, floats, strings,
dictionaries, etc.) have their own corresponding protocols you can implement.
The only thing that's special for types like Array, Int, or String is that the
compiler will automatically infer those types for a literal if there's nothing
that indicates otherwise.

For example:

    
    
      let x = [1, 2, 3] // produces Array
      let y: MyType = [1, 2, 3] // produces MyType
      f([1, 2, 3]) // produces whatever type f() takes

------
dewiz
I like swift's conditionals without brackets, OTOH the syntax for string
interpolation is ugly

~~~
veidr
Ugh, I know it's something that literally every programmer on earth can and
often does bikeshed, but Swift just got string interpolation syntax _wrong_.
Parentheses are something that are often part of the interpolated
expression... they shouldn't be part of the interpolation syntax itself.

~~~
autoreleasepool
Yes, agreed. IMO, curly braces would have made much more sense. It's not even
bikesheding, really. It's just a fact that curly braces are less used in most
written languages. I would also argue that curly braces are a better signal to
the programmer that "something programmatic is happening here", due to their
prevalence as scope delimiters in most popular languages.

Swift's string interpolation doesn't catch my eye like, say, Ruby's does:
`#{my_var}`. It's very easy to gloss over `\\(something_like_this)`. I suspect
they were going for a more "elegant" syntax at the cost of pragmatism.

~~~
sho
I definitely think a general guideline for language designers could be "when
in doubt, make it look like Ruby". The language has its issues, sure, but damn
if it didn't get syntax _just right_.

~~~
mercutio2
I think we will have to agree to disagree on this. Personally, Ruby code is
only marginally better than Perl in terms of line noise I can't read, a
dubious distinction.

------
solidsnack9000
There does seem to be broad agreement across a range of typed languages --
TypeScript, Swift, Kotlin, ES6 + Flow -- about notations for classes, control
flow and data structure declaration.

But true convergence remains far away...

~~~
mathattack
Is this broad agreement due to theoretical alignment, or a deliberate attempt
to increase programmer adoption?

If true convergence happened, there wouldn't be a need for different
languages. :-)

~~~
lmm
I think there is real convergence. All serious new languages have some form of
static typing augmented with some form of type inference. All are lexically
scoped. All have first-class functions and map/reduce/filter. None have
unchecked manual memory management. None have checked exceptions.

There are still areas of debate, but at the same time I think there is real
progress; we have learnt from past mistakes and they won't be repeated.

------
Zarel
Nitpick, the Hello World comparison is more like:

Swift

    
    
        print("Hello, world!")
    

Kotlin

    
    
        fun main(args: Array<String>) {
            println("Hello, world!")
        }

~~~
Larrikin
Kotlin has a REPL

~~~
dcgoss
So does Swift
([https://developer.apple.com/swift/blog/?id=18](https://developer.apple.com/swift/blog/?id=18))
([https://repl.it/site/blog/swift](https://repl.it/site/blog/swift))

~~~
AJRF
You've missed the point. He is saying that to get a hello world going in
Kotlin you don't need to write a func if you are in the context of the REPL.

------
trevor-e
Pretty good list. I don't think the tuple comparison is accurate though, I
thought a data class is basically a value type (like Swift's struct) except
with some stuff like equals, hashcode, and toString calculated for you.

Minor nit: the sort example needlessly uses two lines for the Swift version.

------
pmontra
Some considerations on the syntax (Swift first, Kotlin last in each pair)

    
    
        bad: \(apples + oranges) # using \ is looking for troubles 
        good: ${apples + oranges}
    
        good: label + String(width) # even Ruby requires a .to_s here
        bad: label + width # surprises will follow
    
        good: ["Anna", "Alex", "Brian", "Jack"]
        super bad: arrayOf("Anna", "Alex", "Brian", "Jack") # make the long form optional
    
        good: for index in 1...5 {
        bad: for (index in 1..5) { # the useless ()
    
        bad: extension Double { # why do we need to be so explicit?
            var km: Double { return self * 1_000.0 }
        good: val Double.km: Double get() = this * 1000

~~~
masklinn
> # using \ is looking for troubles

Are you referring to escaping and other special sequences (e.g. unicode
codes)? Though it is odd-looking I actually find it rather smart that they
decided to reuse an existing mechanism for that: aside from delimiters the
only magical character in a string is \ rather than have e.g. both \ and $.

> # the useless ()

My beef is more with 1..5 being inclusive and there apparently being no
exclusive range.

> # why do we need to be so explicit?

Why would you want syntax which is harder to parse, more magical, and has to
be repeated for every addition, instead of an easily marked `extension` block
which neatly parallels `struct` or `class` ones?

~~~
pmontra
About \, yes it's the possible clash with a real quote. More an inconvenience
to the reader that a source of bugs, but also that.

About ranges, Ruby has both .. and ... and after 12 years I don't remember
which is what. Maybe an inclusive one is enough and 1..(n-1)

About syntax in general, it should be easy for developers no matter how hard
it is for the compiler/interpreter to parse it. I don't like to have to type
useless characters. Hence the () around if conditions and this extension
thing. What else can it be? I'm defining a method of a class, no need for a
special block. But I don't understand your "has to be repeated for every
addition" so maybe I'm missing something important here.

~~~
masklinn
> About \, yes it's the possible clash with a real quote.

Clash with a real quote? As in you paste random text from wherever and it
turns out evaluated? You've got the exact same issue in Kotlin.

> About ranges, Ruby has both .. and ... and after 12 years I don't remember
> which is what. Maybe an inclusive one is enough and 1..(n-1)

That's why I like that Swift uses "a..<b" for exclusive, you clearly see the
top-bound being excluded from the range. It's readable and smart design.

> Maybe an inclusive one is enough and 1..(n-1)

I have never missed inclusive ranges in languages with only exclusive ranges
(e.g. Python), the opposite would not be true.

> About syntax in general, it should be easy for developers no matter how hard
> it is for the compiler/interpreter to parse it

That way lie Perl and C++ and undecidable syntaxes, I'm very much opposed to
that.

> I don't like to have to type useless characters.

I don't see what's useless about saying what you're asking for. You define a
struct your use a struct block, you define a protocol you use a a protocol
block, you define an extension you use an extension block. It's readable and
regular.

> But I don't understand your "has to be repeated for every addition" so maybe
> I'm missing something important here.

If you're adding more than one item in Kotlin you have to repeat the receiver
e.g.

    
    
        val Double.km = (thing)
        val Double.miles = (thing)
        val Double…
    

in Swift you just wrap it all in an extension block:

    
    
        extension Double {
            val km = (thing)
            val miles = (thing)
            val ...
        }

------
zem
0..<count is a lovely little piece of language design

~~~
cpfohl
What do you like about it? I was actually thinking the opposite...

EDIT: Genuinely curious, this is not meant to troll or start a war.

I like the more explicit feeling `count-1`. I'd use either...

~~~
seanwilson
It confused me as well. "0.. is less than count"?

~~~
Watabou
Personally, I find that just having "0..count" requires a bit of thinking on
my part trying to decide if it's inclusive or not.

"0..<count" instantly tells me that it's not including value, and follows the
matematical interval notification [0..count] vs [0..count)

~~~
seanwilson
I'd prefer 0..count or 0..(count - 1) then.

------
itaris
It is worth noting that both languages also resemble Scala.

see:

[https://leverich.github.io/swiftislikescala/](https://leverich.github.io/swiftislikescala/)

[https://agilewombat.com/2016/02/01/scala-vs-
kotlin/](https://agilewombat.com/2016/02/01/scala-vs-kotlin/)

~~~
divanvisagie
I personally think this exercise is rather odd in the first place. A lot of
modern languages seem to have a same base syntax and these comparisons over
simple operations is like taking all of the latin based languages and showing
all the words that look similar.

~~~
pkolaczk
Actually Kotlin is just Scala dumbed down by taking out the most powerful and
interesting features like higher kinds, implicits, monads or macros. Which
makes it just a Java 8 with a bit nicer syntax.

------
Vekz
Syntax should be a personal preference, installable module built on a
standardized AST which compiles to whatever VM.

~~~
smt88
Microsoft's CLR is not unlike this idea. JavaScript transpilers are also
similar.

------
seltzered_
Two Kickstarter mobile engineers (Brandon Williams & Lisa Luo) just gave a
talk on this at uikonf two days ago, where they walked through the
similarities and small differences. Talk should be online soon.

The kickstarter apps are open source so you can compare it yourself.

------
annnnd
I wonder if Google's support for Kotlin has anything to do with Oracle's
lawsuit over Java, or is it just a cherry on the top? :)

------
redleggedfrog
That's a great page - it's like one really cool language could come from the
combination of the two. Each taken on it's own, they have their warts.

------
kartickv
As an iOS developer who's looking to port to Android, this makes it easier to
manually port my Swift code to Kotlin. But I wish there were automated tools.
If two languages are this similar conceptually, such a tool should be easy to
write, and handle the majority of cases.

I don't mind if this tool prohibits a few features (pattern-matching in Swift,
say), even if it's considered idiomatic, because not having to maintain
another codebase saves more than enough productivity to make it worth it.

Does such a tool exist?

------
scotbond
Kotlin is the same jvm crap like Java. Please do not dare to compare it to
Swift with its amazing llvm complier. True programs runs on true machine
specific bytecode, not on stupid virtual machines that consumers every
available cpu and memory (which leaks like hell). Please new programmers,
syntax is BS. Learn to compare by looking at internals and advanced feature
set and capabilities. Kotlin is a fad!

------
nathan_f77
Why not merge Swift and Kotlin?

Seems like they are very similar languages, with similar goals. They both want
to be cross-platform. I suppose the competition is healthy, but at some point
there's just a lot of duplicated effort. Although, I guess if they're both
using LLVM, then it's not such a big deal. Maybe one day we'll see libraries
that can be used by both Kotlin and Swift.

------
Myrth
The last example made me wonder if it's possible to do something like this:

val oneInch = 2.54.mm println("One inch is $oneInch.cm() centimeters")

~~~
pvdebbe
My hunch says that in order to be anywhere usable, any extra arithmetic must
be done inside curly brackets, much like in Perl or PHP. It makes sense and is
easy to parse for both human and compiler.

    
    
      println("foo ${oneInch.cm()} bar")
      println("fez $quux")

------
FullyFunctional
325 comments presently and sadly no one commented on what I find most exciting
about Swift: integer overflow is trapped! FINALLY (the only other sane option
is multi-precision integers, like in Scheme or Integer in Haskell). Does
Kotlin do the same?

I presume Kotlin also traps out-of-range array accesses.

------
goshx
Is there any tool that converts one to the other?

I think it is worst to have such similarities with very small different
details than having completely different languages. For a developer working on
both ecosystems it feels like hell to remember the tiny details.

------
makmanalp
What ever happened to xtend, which I found a nicer balance between Java and
Python-ish. Anyone have any experiences with it?

[https://eclipse.org/xtend/](https://eclipse.org/xtend/)

------
codecamper
Neither of them do what I want which is to write some logic code once (logic /
network / persistence) and run it both on Android and on iOS.

What I do now is use j2objc, but here I am stuck in Java land.

------
rgun
waiting for a language that transpiles to Kotlin and Swift

~~~
nathan_f77
Here's an attempt to transpile Kotlin to Swift:
[https://github.com/moshbit/Kotlift](https://github.com/moshbit/Kotlift)

(Not updated recently.)

------
zachmax
I've never really heard of Kotlin, is it supposed to be a Java replacement?

~~~
drampelt
Yes, it runs on the JVM and is 100% compatible with Java code. While it was
fairly easy to use Kotlin with Android before, Google just announced first-
class support for it at IO.

------
aldo712
Would be great if someone could add a third column for Java.

------
crimsonalucard
algol based languages are all similar. It's like comparing scheme and closure.

------
cel1ne
* A feature I like about kotlin are the receivers, with which you can write type-safe builders: [https://kotlinlang.org/docs/reference/type-safe-builders.htm...](https://kotlinlang.org/docs/reference/type-safe-builders.html)

* Multiple receivers are possible enabling extension methods like this:
    
    
        class EnglishToGermanDictionary {
    
           val translations = mapOf<String, String>(
              "dog" to "Hund"
           )
    
           /* extension method for string in the context of dictionary */
           val String.inGerman get() = 
              translations[this@String]
        }
    
        /* usage */
        with (EnglishToGermanDictionary()) {
           val word = "dog"
           println("The translation of $word is ${word.inGerman}")
        }
     
        "cat".inGerman ---> compile error, method not found
    
    

* Built-in Singletons are also very convenient. Swap the word `class` for `object` and you get a singleton.

* The article left out lambdas. The function:
    
    
        fun greet(name: String, day: String): String {
            return "Hello $name, today is $day."
        }
    
        Can also be written as
    
        val greet = {name, day -> "Hello $name, today is $day."}
    
    

* The compiler is really smart in infering types. Extension values don't need type-specification, e.g.:
    
    
        val Double.km get() = this * 1000
    
    

* "when" in Kotlin doesn't need an argument, you can write arbitray rule-sets with it, with correctly inferred conditions:
    
    
        val myVar = when {
            stack.isEmpty() -> true
            x == null -> false
            currentIdx >= a && obj is MyType -> true   /* here x has been inferred to be not null from the previous branch! */
            else -> when {
                user.isPresent() -> calculateSomething()
                else -> throw IllegalStateException()
            }
        }
    

* sealed classes allow you to limit inheritance and get error when you miss something in a when
    
    
        /* you actually don't have to nest the classes this way, but you can */
    
        sealed class Expr {
           sealed class IntExpr : Expr {
              class Plus(val left: Int, val right: Int): IntExpr
              class Minus(val left: Int, val right: Int): IntExpr
           }
    
           sealed class StringExpr : Expr {
              class Substring(val str: String, val start: Int, val end: Int): StringExpr
           }
        }
          
        /* Usage: */
        val x: Expr
        when (x) {
           is Substring -> ...
           is Plus -> x.left + x.right
    
           /* compile error, we forgot to handle "Minus" from above */
        }

~~~
_pmf_
The receivers mechanism is kind of nice; reminds me of this[0], except that in
Kotlin, everything is still statically typed. It's a really clean way to
implement Trygve Reenskaug's DCI architecture.

[0] [http://www.p-cos.net/documents/contextl-
soa.pdf](http://www.p-cos.net/documents/contextl-soa.pdf) (there was once an
article called "ContextL : The Holy Grail of Business App Development", but
this seems to be no longer available

------
kodfodrasz
Could someone tell me the meaning of _ in this Swift code:

    
    
        func greet(_ name: String,_ day: String) -> String {
            return "Hello \(name), today is \(day)."
        }
        greet("Bob", "Tuesday")
    

In me prior experience usually _ denoted an unused parameter/variable.

Also: I find the string interpolation syntax ugly... The syntax choices in
Swift are curious, but not the most aesthetical/practical in my opinion.

~~~
Watabou
Swift has both external and internal parameter names for functions. This is to
make API design more readable, easier to parse through.

For example, you can have a function like so:

    
    
        func greet(with greeting: String, to personName: String) {
            print("\(greeting), \(personName)!")
        }
    

In the above code, "with" and "to" are external names, and are only available
when calling the function but are not available inside the function itself. So
you would call this function like so:

    
    
        greet(with: "Hello", to: "Bob")
    
    

Now if you want to exclude the external name to call the functions, you use
the "_" syntax. So you're right that it denotes an unused parameter. In this
case, it's an unused external parameter name.

~~~
saghm
Having never used Swift, it feels like the syntax is being optimized for the
less-common case; are named parameters considered the "default" choice in
Swift, and is using different external names so common that it's worth
cluttering the syntax for functions without external parameters in order to
make the their own syntax easier?

~~~
ridiculous_fish
Named parameters are very much the default in Swift. Positional parameters are
rare exceptions.

The internal/external name divide often works out beautifully. For example,
let's equip Double with a multiply-add. An idiomatic Swift signature:

    
    
        extension Double {
          func multiply(by multiplier:Double, adding summand:Double) -> Double {
            return self * multiplier + summand
          }
        }
    
        print(3.multiply(by:4, adding:5))
    

Erase punctuation and you have:

    
    
        func multiply by multiplier adding summand
    
        print 3 multiply by 4 adding 5
    

The caller sees an action (multiply by, adding), the callee sees nouns
(multiplier, summand). It's fantastically readable.

~~~
kybernetikos
The javascript equivalent would be something like

    
    
        Number.prototype.multiply = function({by:multiplier, adding:summand = 0}) {
    	return this * multiplier + summand
        }
    
        console.log((3).multiply({by: 4, adding: 5}))
    

But of course, javascript APIs are hardly ever written like that. I think it's
interesting how the norms of your ecosystem and very small differences in
ergonomics in expression make a big difference in behaviour.

------
kozak
Here in Ukraine it would be very hard to get adoption of a programming
language that is named after a Russian military base. This is the rare case
where bad naming choice really hurts. No matter how good is the language, you
will have to hear and pronounce that name many times a day, and even associate
yourself with it (e.g. "a Kotlin developer" in your resume). Not something to
be taken lightly.

~~~
Apocryphon
If they open source it, maybe someone should fork it called Kiev.

~~~
kozak
Ironically, the name "Kiev" would be no less offensive becuase this spelling
of the name implies that this is a Russian city, not a Ukrainian one. The
official and correct spelling is "Kyiv", see [http://kyiv.of-
cour.se/](http://kyiv.of-cour.se/) for explanations why.

~~~
cgb223
Ironically, the name "Kyiv" would also be no less offensive since it is
written in Latin characters non native to Ukraine instead of the Ukrainian
alphabet, which is a derivative of the Cyrillic alphabet. The official and
correct spelling is "Київ"

~~~
kozak
Totally not. Many newly-installed signs in Kyiv are bilingual, in Ukrainian
and in English. We have official rules for transliterating Cyrillic into Latin
which the government uses.

------
jbverschoor
I don't get it. Kotlin was a clone of swift. So the title is wrong.

~~~
dagw
Kotlin was first released at least a couple of years before anyone outside of
Apple had even heard of Swift.

~~~
jbverschoor
Ah ok. Wikipedia says 2011.. Didn't hear about kotlin until a few months after
swift was released

------
kaxi1993
Both of them are like javascript

------
alper
Kotlin would be unnecessary if Apple would do the work to interop/compile
Swift both to the JVM ecosystem and the JavaScript one.

Unfortunately Apple's ambition on swift seems to have stalled.

