22 ms·
Swift is like Kotlin
- zem 9y ago0..<count is a lovely little piece of language design
- cpfohl 9y agoWhat 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 9y agoIt confused me as well. "0.. is less than count"?
- GavinMcG 9y ago".." has a meaning – why are you leaving it out of the translation?
- seanwilson 9y agoI'd usually use ".." in the context of e.g. "2..3" to express a range but "<" to express a condition so I don't find it natural.
- Watabou 9y agoPersonally, 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 9y agoI'd prefer 0..count or 0..(count - 1) then.
- proyb2 9y agoI believe it was discussed in Swift Evolution, not confusing. 0...1 //0 to 1 Note: triple dot. 0..2 //error: repl.swift:1:2: error: use of unresolved operator '..' 0..<1 //0 to <1
- mikeash 9y agoAdd spaces for clarity: 0 ..< count I think Swift programmers should adopt this style.
- tomfitz 9y agoWhen I see "0..n" I wonder whether the range is inclusive or exclusive of n. When I see "0..<n" I know the range is exclusive of n.
- sillysaurus3 9y agoYes, but the corresponding design decision would be "0..=n". Swift's "0...n" is a bit less obvious. Also, exclusivity is almost always what you want, so "0..n" should just default to exclusivity and "0...n" could be inclusive.
- saghm 9y agoAs an alternative opinion, I personally hate when ranges are exclusive by default. In addition to it feeling somewhat unintuitive to me that I need to use range(0, 6) to include 5, it also makes downward ranges quite awkward, e.g. needing range(5, -1) to count from 5 to 0.
- dbaupp 9y agoExclusive by default is designed to fit with 0-based indexing (0..length(v), instead 0..(length(v)-1)). That said, this thinking is less relevant in languages with iterators/ranges and doubly so ones that offer a way to explicitly, but abstractly, iterate over the indices of a vector/array. On the point of downward ranges, you can often reverse the range explicitly, rather than swapping the endpoints, like reversed(range(0, 6)) or range(0, 6)[::-1] in Python (vs. range(5, -1, -1)). Of course, this isn't nearly as syntactically nice as range(5, 0)... but that comes with its own problems: automatically iterating backwards in ranges has been really annoying every time I've encountered it (mainly in R), requiring extra care and a pile of extra ifs and/or mins & maxs.
- saghm 9y agoI understand the benefits, I just personally don't prefer it. But this is just my subjective opinion.
- 9y ago
- ridiculous_fish 9y agoHow is the inclusive range operator implemented in Kotlin? Something like `for (i in 0..count)` needs to iterate count + 1 times, which may overflow the size of count's type - annoying to implement.
- kaeawc 9y agoIn Kotlin it's much more common to write the following, which is exclusive: count.forEach { // do things }
- chc 9y agoI don't see where the overflow would come into play since count is the terminal value and count is necessarily representable in its type.
- coldtea 9y ago>needs to iterate count + 1 times, which may overflow the size of count's type - annoying to implement How's that different from: for (int i=0; i<=count; i++) in e.g. C99?
- zem 9y agoit's always confusing, in languages with ranges, whether the range includes the second boundary element or not. it's purely a matter of convention, after all. ruby has a..b and a...b, but even after years of using the language i have to look up which is which. a..<b and a..b is perfect notation - once you know the language handles both cases, a..<b is very clearly "the range of numbers from a, and remaining strictly less than b", and "a..b" is "the range of numbers from a up to and including b". as for the "count - 1", it's not too bad because i find "inclusive" more intuitive than "exclusive" for the a..b notation, and that does make it explicit that you're not including b, but it's visual clutter in much the same way that having to iterate an array via "for i = 0 to len - 1" is.
- throwaway91111 9y agoWhy is it a..b instead of the logical a..=b or a..<=b?
- ves 9y agoYou only need to know that the language handles one explicitly, since there's two choices, so you might as well take the (more common | uglier to express) case and give it the "cleanest" special syntax: no special syntax.
- deleted 9y ago[deleted]
- deleted 9y ago[deleted]
- ptx 9y ago"a..b - 1" can also be written as "a until b" in Kotlin.
- Filligree 9y agoWhich is not as obvious. I much prefer a..<b.
- captaincrowbar 9y agoIn the early beta release of Swift 0.x, they used x..y for half-open ranges and x...y for closed ranges. This confused people (especially since Ruby already used the same operators but the other way around), so they changed the half-open operator to x..<y.
- deleted 9y ago[deleted]
- mikeash 9y ago0 ... count-1 fails when count is equal to the smallest value the type can represent (for example, if it's 0 and unsigned).
- jlg23 9y agoIndeed a clear syntax. OTOH, a "loop .. for .. {upto, below} count" leaves less questions in a casual code review :)
- desdiv 9y agoI prefer explicit words over symbols, like in Scala: scala> 1 to 3 scala.collection.immutable.Range.Inclusive = Range(1, 2, 3) scala> 1 until 3 scala.collection.immutable.Range = Range(1, 2)
- Cyph0n 9y agoAgreed, Scala's approach to ranges is one of the best out there from my experience.
- menage 9y agoAs someone who's never programmed in Scala, it's not intuitive to me at all that "until" means exclusive, given that "to" (which is basically a synonym) means inclusive.
- lauritzsh 9y agoHow would you feel about > 1 through 3 # [1, 2, 3] > 1 until 3 # or 1 to 3 # [1, 2] as explicit word range notation?
- throwaway91111 9y agoI can't tell whether this is sarcasm or not. What does the '<' mean in this case? I'm assuming an exclusive upper bound.
- taurath 9y agoRead it as "For 0 to count" basically. "0... (spread operator) less than 0. It seems confusing to me as well at first read but I'm used to writing for loops by hand uphill both ways.
- Larrikin 9y agoIs there any language where the meaning isn't immediately clear? I haven't seen a language that didn't differentiate between '<=' and '<'. The syntax of just '..' is a little unclear at first however, but it is simply a requirement of learning the language and the idioms
- zem 9y agoit's not. i've never used swift, and the meaning was instantly obvious - i'd call that a very elegant solution to a common problem i've seen in several languages.
- tomfitz 9y agoAn alternative approach is Guava's Range class: Range.closed(1,5) == [1,5] Range.open(1,5) == (1,5) Range.openClosed(1,5) == (1,5] Range.closedOpen(1,5) == [1,5) Range.greaterThan(1) == (1,infinity) Range.atLeast(1) == [1,infinity) That class always strikes me as having high power-to-weight. It has methods like encloses(anotherRange), contains(aValue), and others. https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Range.html https://google.github.io/guava/releases/19.0/api/docs/com/go...
- saghm 9y agoShould the second "closed" be "closed Open" (with the corresponding change to the rest of the line)?
- tomfitz 9y agoFixed, thanks.
- derefr 9y agoWhat does a Guava two-Integer-element array literal look like?
- tomfitz 9y agoSorry, I didn't explain myself well. Range.closed(1,5) is the syntax used to refer to what a mathematician would call [1,5]. Guava is just a Java library. In Java 9, a two-Integer-element list literal will be List.of(9000, 9001).
- nathan_f77 9y agoToo verbose for me. I always prefer short syntactic sugar.
- dewiz 9y agoI like swift's conditionals without brackets, OTOH the syntax for string interpolation is ugly
- veidr 9y agoUgh, 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 9y agoYes, 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 9y agoI 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.
- contras1970 9y ago> but damn if it didn't get syntax just right. Yeah, like the symmetry of `do` / `end`! /s
- mercutio2 9y agoI 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.
- kodfodrasz 9y agoCould 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.
- deleted 9y ago[deleted]
- myhf 9y ago_ in function parameters indicates that a parameter can be passed by position, without its name. Without _ you would have to call greet(name: "Bob", day:"Thursday") but with _ you can call greet("Bob", "Thursday")
- Larrikin 9y agohttps://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html https://developer.apple.com/library/content/documentation/Sw... Swift forces you to use named parameters if you don't do that.
- deleted 9y ago[deleted]
- deleted 9y ago[deleted]
- Watabou 9y agoSwift 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.
- itaris 9y agoIt 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 9y agoI 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 9y agoActually 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.
- redleggedfrog 9y agoThat'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.
- chc 9y agoI 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 9y agoI 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).
- s_dev 9y ago>Kotlin came across as strangely familiar, though, and eventually I realized it's because it looks like Swift -- which I was slow to notice because my iOS app is in Objective C for irritating legacy reasons. And of course now I know that's backwards: Kotlin predates Swift by several years, so it's more accurate to say that Swift is like Kotlin. -Yegge
- krallja 9y agoIn fact, it's linked from the Yegge post.
- mastazi 9y agoOP 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.
- johnhattan 9y agoYeah, my first impression was "This is exactly like Haxe". They definitely went through some steps to make it familiar.
- solidsnack9000 9y agoThere 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 9y agoIs 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 9y agoI 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.
- solidsnack9000 9y agoSome of it is due to theoretical alignment. For example, succinct function expressions come out of the the desire to simplify use of functional programming. Another example is the adoption of ML-style type notation: we want people to use static types, we want it to be easy, and we want types to be expressive -- <var>: <type> allows <type> to contain some spaces and punctuation while still being clear.
- Cyph0n 9y agoDon't forget that Scala preceded all of the languages you've listed, which in my opinion shows where the inspiration came from for some of them. Of course, I'm sure that Scala drew inspiration from some of its predecessors.
- solidsnack9000 9y ago
- trevor-e 9y agoPretty 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.
- deleted 9y ago[deleted]
- Vekz 9y agoSyntax should be a personal preference, installable module built on a standardized AST which compiles to whatever VM.
- smt88 9y agoMicrosoft's CLR is not unlike this idea. JavaScript transpilers are also similar.
- kaxi1993 9y agoBoth of them are like javascript
- Myrth 9y agoThe 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 9y agoMy 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")
- Zarel 9y agoNitpick, the Hello World comparison is more like: Swift print("Hello, world!") Kotlin fun main(args: Array<String>) { println("Hello, world!") }
- Larrikin 9y agoKotlin has a REPL
- deleted 9y ago[deleted]
- dcgoss 9y agoSo 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 9y agoYou'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.
- Tanegashima 9y agoSo does Swift
- amasad 9y agoWe also support kotlin as of yesterday https://repl.it/site/blog/kotlin https://repl.it/site/blog/kotlin
- NathanFlurry 9y agoOne 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.
- NathanFlurry 9y agoYes, I know about Kotlin Native, but it's not quite there yet.
- Tanegashima 9y agoStill doesn't make up for Swift's language superiority.
- Tanegashima 9y agoExcellent C and Objective C interoperability too. As for the post, it's ridiculously fanboyish. The same comparison could be made with other older languages towards Kotlin. Microsoft F# comes to mind, for example.
- guelo 9y agoKotlin Native ships with an ARC. But depending on the application ARC can be a disadvantage since it can't automatically handle reference cycles like Kotlin on the JVM can.
- kbd 9y ago> [Kotlin Native] features automatic reference counting with a cycle collector on top, but what the final memory management solution(s) will look like is unknown at this point. https://blog.jetbrains.com/kotlin/2017/04/kotlinnative-tech-preview-kotlin-without-a-vm/ https://blog.jetbrains.com/kotlin/2017/04/kotlinnative-tech-...
- masklinn 9y agoSo it's not ARC (in the Swift sense), it's just RC + cycle breaker.
- kozak 9y agoHere 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 9y agoIf they open source it, maybe someone should fork it called Kiev.
- kbd 9y agoKotlin is open source: https://github.com/JetBrains/kotlin https://github.com/JetBrains/kotlin
- AlexeyBrin 9y agoIt is open sourced, Apache 2 license https://github.com/jetbrains/kotlin https://github.com/jetbrains/kotlin
- kozak 9y agoIronically, 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.
- lngnmn 9y agoLol! just lol! Swift is, perhaps, the most carefully designed modern language based on a small set of explicit principles, articulated "philosophy" (clarity at the use site) crafted with an unprecedented attention to details (sometimes zeal is better that a standardized kitchen-sink syndrome of C++ or over-engineering narcissism of Scala), while Kotlin is just an unduly ambitious crap, like everything Russian.
- sctb 9y agoWe ban accounts that break the guidelines like this, so please don't do it again. https://news.ycombinator.com/newsguidelines.html https://news.ycombinator.com/newsguidelines.html
- Black-Plaid 9y agoIt'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 9y agowhile we're at it http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.34.1618 http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.34.16...
- throwaway7645 9y agoWhy are you citing an FP comp Sci professor? I must've missed something
- agumonkey 9y agoseeing reduce in swift made me think about the universality of fold, which is the paper linked.
- throwaway7645 9y agoAh, was about to say that all goes back to lambda calculus by Church and could be found in Lisp probably around ~1958.
- agumonkey 9y agoActually I think there's a relation with exponentials and integral calculus. Or anything hyper-iteration related.
- timjver 9y agoThere's a PR that fixes one of them which was filed on December 22 of last year... Yikes.
- crimsonalucard 9y agoalgol based languages are all similar. It's like comparing scheme and closure.
- seltzered_ 9y agoTwo 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.
- cel1ne 9y ago* 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.html https://kotlinlang.org/docs/reference/type-safe-builders.htm... * 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_ 9y agoThe 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
- deleted 9y ago[deleted]
- deleted 9y ago[deleted]
- rgun 9y agowaiting for a language that transpiles to Kotlin and Swift
- nathan_f77 9y agoHere's an attempt to transpile Kotlin to Swift: https://github.com/moshbit/Kotlift https://github.com/moshbit/Kotlift (Not updated recently.)
- martijn_himself 9y agoDoes 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.
- pmontra 9y agoI agree, it leaves a bad taste in the mouth. It's even worse than old PHP's array(). I'll pick short forms all the time: lists with (), dictionaries/hashes with {}.
- ansible 9y agoPython does this too, and I dislike it slightly. I'd prefer uniform syntax for collections, such as in Lua or golang.
- masklinn 9y ago> 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 9y agoI 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 9y agoIt'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
- nathan_f77 9y agoWhy 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.
- pmontra 9y agoSome 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 9y ago> # 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 9y agoAbout \, 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.
- jdsampayo 9y ago
- codecamper 9y agoNeither 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.
- _31 9y agoPast 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 9y agoI 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_ 9y ago> 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_fuchsia_smartphone_os_dumps_linux_has_a/dhbjmvx/ https://www.reddit.com/r/programming/comments/6a026o/googles... for a pretty damning review
- kyrra 9y agoInteresting link. One of the relies to the review of fuchsia gives a different view as to why there are inefficiencies in it: ..."All of the things you mentioned have known solutions making it easy to improve down the road."...[0] [0] https://www.reddit.com/r/programming/comments/6a026o/googles_fuchsia_smartphone_os_dumps_linux_has_a/dhc34j8/ https://www.reddit.com/r/programming/comments/6a026o/googles...
- annnnd 9y agoI 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? :)
- aldo712 9y agoWould be great if someone could add a third column for Java.
- jbverschoor 9y agoI don't get it. Kotlin was a clone of swift. So the title is wrong.
- Pharylon 9y agoKotlin predates Swift.
- dagw 9y agoKotlin was first released at least a couple of years before anyone outside of Apple had even heard of Swift.
- jbverschoor 9y agoAh ok. Wikipedia says 2011.. Didn't hear about kotlin until a few months after swift was released
- sproketboy 9y agoSwift is like Kotlin except it's much worse.
- goshx 9y agoIs 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.
- Unknoob 9y agoThe 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 9y agokotlin 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.
- flaie 9y agoIn kotlin you can also write: var name: String? // some code name?.let { // here name is not nil and can be accessed via variable "it" } // or name?.let { name -> // here name shadows the previous variable, and is not nil }
- phkahler 9y agoI 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.
- swsieber 9y agoKotlin is looking at expanding it's targets beyond js/ts and java to be able to target native, and I think it's with iOS in mind...
- dannyr 9y agoImagine having just one programming language where there is likely one gatekeeper. I doubt language innovation would happen with that setup.
- BaronSamedi 9y agoImagine 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.
- alper 9y agoKotlin 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.
- alper 9y agoKotlin 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.
- jnbiche 9y agoKotlin 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 9y agoMaybe you haven't checked out Kotlin lately? Kotlin has somewhat pattern matching: https://kotlinlang.org/docs/reference/control-flow.html#when-expression https://kotlinlang.org/docs/reference/control-flow.html#when... Tail call optimization: https://kotlinlang.org/docs/reference/functions.html#tail-recursive-functions https://kotlinlang.org/docs/reference/functions.html#tail-re... 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 9y ago> 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.
- makmanalp 9y agoWhat 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/
- zachmax 9y agoI've never really heard of Kotlin, is it supposed to be a Java replacement?
- drampelt 9y agoYes, 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.
- FullyFunctional 9y ago325 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.
- scotbond 9y agoKotlin 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!
- kartickv 9y agoAs 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?