Swift is like Kotlin
nilhcem.com
nilhcem.com
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.
Kotlin has somewhat pattern matching: https://kotlinlang.org/docs/reference/control-flow.html#when...
Tail call optimization: https://kotlinlang.org/docs/reference/functions.html#tail-re...
Type classes: 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.
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.
Sealed classes are an odd/wonky take on sum types, they're not even remotely close to type classes.
recursive data structures: I don't get this one, kotlin has all the java api available and all the third party libraries. As java has been here for much longer than swift I guess that swift is lacking more here than kotlin.
Tail call optimization: kotlin has the special word tailrec for this
Yes, kotlin has a lot of things. It also has co-routines like in go, it also compiles to java script and much more.
The reason Google is supporting kotlin and not swift or scaala is because they have to do nothing to support it. Kotlin compiles to bytecode, so it doesnt matter your code is written in java or kotlin because when you compile it it is bytecode at the end. Scala needs to add a runtime when compiling to bytecode, it takes much longer to compile than kotlin and it is not fully compatible with java as kotlin. And Swift it is just something completely different, they should change the virtual machine in order to support it.
Recursive data structures: Yeah, for some reason I wrote recursive data structure when I was thinking of algebraic data types, like Scala can encode with case classes. I often use them in Scala or OCaml to make recursive data structures which is why I mistakenly used that term instead of ADTs.
TCO: glad to see I was wrong. Kotlin added support for this in the past year.
Android: I realize that to support Swift on Android, Google would need to do significant work, but they wouldn't have to change the VM since Swift could also be compiled to Dalvik bytecode. But obviously that would be a lot of work. I only mention Swift since there were rumors in the past that Google was considering fully supporting Swift on Android.
Plus, to be clear, you can run Swift on Android now using the native SDK, just not on Dalvik for making GUI apps.
Actually not. Not now, probably it was the case at the begining of the language.
> algebraic data types
they removed some restriction of sealed classes in 1.1. So I am not sure this is true anymore.
The memory management in Swift is completely different than in Java. That is the main reason you need to make changes in the virtual machine. JVM uses the garbage collector while swift uses reference counter.
This is nonsense? It doesn't need any more "runtime" than Kotlin does.
> it is not fully compatible with java as kotlin.
This is a lie. (I don't say this lightly, but I've seen it too often from too many kotlin advocates for it to be an innocent mistake)
Last time I checked you needed like 500kb of libraries for any scala program compiled to Android. Kotlin is a few kb. Kotlin is a small addition to the java API, Scala needs much more things.
> it is not fully compatible with java as kotlin.
As far as I know, the way scala treats types and functions make it that sometimes you cannot call scala code from java. Well, you can most times but requieres a lot of wrappers. This doesn't happen in kotlin.
I learn scala few years ago, my memory is weak and things may change. But I wanted to use it for android and give up quite quickly because of lot of issues. For kotlin was like love at first sight. No problems at all.
30kb for Scala is the figure elsewhere in this thread and that sounds a lot more in line with my experience. Note that you never have to use e.g. Scala collections if you don't want to (and thanks to typeclasses you can write elegant code that works with both Scala collections and Java ones, so you can reuse libraries across both).
> As far as I know, the way scala treats types and functions make it that sometimes you cannot call scala code from java. Well, you can most times but requieres a lot of wrappers. This doesn't happen in kotlin.
Nope. There's no difference, just kotlin propaganda.
My understanding is that Swift has these to some extent ("let" vs "var", structs being immutable etc). And since Kotlin is built on JVM compatibility I _assume_ that Kotlin does not support an immutable style of programming. Maybe someone here has more clarity on this.
Both Clojure and Scala that run on JVM have strong support for immutability, so it's quite possible on the JVM.
And yes, Swift has let binding, and other features to support immutability.
And for structures you have list, mutablelist, map, mutablemap, etc.
What else do you want?
According to this http://stackoverflow.com/questions/33727657/kotlin-and-immut... Kotlin does not support true immutability.
For immutability to be practical one would need to implement structural sharing in their collections otherwise copying would be prohibitively expensive.
This Java library seems to be trying to implement this. http://www.vavr.io/
Again, I am not saying that Kotlin does not support immutability, just trying to get to the bottom of the reality of it.
out of curiosity, what cases will you use an immutable collection instead of a read-only? I cannot imagine any use case where immutable is a gain over read-only.
Consider the situation where you had a linked list with 10,000 elements and you wanted to return a new list with one new element added to the 'head' of the list. With "read-only" you would literally have to make a new linked list with 10,001 elements which would kill performance.
While semantically correct, immutability via deep-copying is very impractical. So, immutability (of Collections in particular) needs to be implemented via structural sharing of elements.
In the above example, with structural sharing, the new list would have the new element and inside would point to the old 10,000 element list but the whole 'structure' would appear to you as just a normal list.
In essence if the original object implements a List _interface_, then the new one should as well. If you do all of this, then you've essentially implemented immutability and structural sharing. But then you have to do this for 10 other Collection types as well.
Now, you could do all this, but I could do it as well and do it differently. Then my function which took MyList as argument would not interoperate with your function that wants to pass YourList as argument.
Something as fundamental as an (immutable) collection needs to be standardized so that all functions can take these and return them and thus compose easily.
This is the case with languages that implement immutability like Elixir, Haskell etc.
This needs to be built into the language or somehow standardized by the community.
With lack of standardization of immutable collections, there would be lots of different ways that libraries would implement immutability. This would result in losing one of the main benefits of functional programming (i.e. awesome composability).
The underlying host doesn't imply anything about language support as that's handled at the compiler level, not at the machine or VM level.
Even in Haskell data isn't immutable if you have a debugger or modify the machine code. It's simply a tool provided and enforced solely by the compiler - other JVM languages do support it like Clojure or Scala.
Swift, they'd have to redo just about their entire stack, as Swift doesn't run on the JVM (Swift can be used with the NDK to build NDK libraries, but it's not standard to build a full app, outside of games, with that).
Scala has had big issues with the size of it's library that still haven't been resolved, and the new versions of Scala require Java 8, which only the beta version of Android supports right now.
Same goes for Swift.
Any "hybrid oo functional" language will not do the functional thing as well as a dedicated functional language. If you're still gluing things together with types, functions will never be quite as first-class as they should be.
If you want to compare them, going over the differences would be a lot more illuminating.
-Yegge
[1]: https://flutter.io/
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... for a pretty damning review
..."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...
[0]https://arstechnica.com/gadgets/2017/05/googles-fuchsia-smar...
I was under the impression that pretty much all the frontend work at google was compiled from Dart.
It's also used for Google's internal CRM (Greentea), and Google Fiber.
[0] http://news.dartlang.org/2016/03/the-new-adwords-ui-uses-dar...
[1] http://news.dartlang.org/2016/10/google-adsense-angular-dart...
It may be true for Swift but Google never claimed Kotlin is replacement of Java. I guess people are getting overly excited and making claims that Google did not. Kotlin is low effort developer friendly move by Google. Jetbrains will do work on language and tooling and Google would provide some Android-Kotlin related docs and support.
let sorted = [1, 3, 6].sorted()
let sum = [1, 3. 6].reduce(0, +)
as examplesSwift 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 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
}https://blog.jetbrains.com/kotlin/2017/04/kotlinnative-tech-...
> https://blog.jetbrains.com/kotlin/2017/04/kotlinnative-tech-...
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.
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.
I never did anything in VS though, cause its interface always turned me 180 after first run. And I can write Makefile and .gvimrc from scratch much faster than it installs itself.
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.
I use IntelliJ/Android Studio for Java, and that's about it.
As chance might have it, the Swift documentation has a section on programming for Android: https://github.com/apple/swift/blob/master/docs/Android.md
And RoboVM has an article on using Kotlin for iOS development: https://robovm.com/kotlin-for-cross-platform-mobile-app-deve...
I honestly didn't know that I could use either Kotlin OR Swift for both platforms. But which would be easier to get running on Windows? I also need to write a version that works on the web, and I've heard that Kotlin can transpile to JS. So that's pretty amazing if that works.
Otherwise I was considering C, C++, or Rust.
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.
I doubt language innovation would happen with that setup.
Can you cite an example?
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.
:D
I think you meant Java and now Kotlin? Google never recommended Dart for Android development. They have Flutter which uses Dart, but that positions itself as a cross-platform way to build apps and doesn't have any support from Android tooling or things like that. It also still positions itself as an alpha, so do with what what you will.
But Kotlin also works just fine on JVM. So Kotlin works on MacOS, Windows, Linux, and now Android. That sounds pretty cross platform to me. Kotlin is also not a language from Google, so I don't know why you're annoyed with Google on this one. Kotlin is from JetBrains.
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.
I'll pick short forms all the time: lists with (), dictionaries/hashes with {}.
Well yeah, except it's really that Kotlin does not have array literals at all, arrayOf is just a variable-arity function.
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() takesIt is more ugly for arrays but much more helpful for other things. And it also make sense with the lists as you said.
val shoppingList = Seq("catfish", "water", "tulips", "blue paint")
"Foo" to "Bar"
Is also nonsensical. What's wrong with ':'?
The to method constructs a Pair object from its arguments, so
"Foo" to "Bar"
is just a prettier way of writing: Pair("Foo", "Bar")
The mapOf function (which is just a normal function) takes a variable number of Pair objects as parameters.In practice, it's something I stopped caring about within the first hour.
Then again, mikeash's comment pitches a more interesting idea: [] as generic collection literal syntax that depends on inference / annotation to pick a concrete implementation. Best of both worlds. I'd just remove the Array default.
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.
Yeah, like the symmetry of `do` / `end`! /s
Hyperbole much?
Not trying a language because one dislikes the syntax for one of 2000 features it has, and not even the most important one, looks hyperbolic to me.
"blah blah \(f(g(42)))"
Seems fine to me.Why not? It's not like there's any conflict. You can use parens inside the interpolated expression just fine.
But true convergence remains far away...
If true convergence happened, there wouldn't be a need for different languages. :-)
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.
// Type indicated with `:`, type follows variable; value follows type.
variable: Type
variable: Type = "value"
// Generics with <>
strings: List<String>
// Operator overloading.
text = "a" + "b"
num = 1 + 2
// Capitalize type names.
class TheClass { ... }
// Use braces for delimiting.
class TheClass { ... }
Most of the conventions we're talking about were adopted by Scala; but we can see they also predate Scala. Many can be found in C++. The type/variable notation is very old, going back to ML and truthfully going back to mathematical notation.Swift
print("Hello, world!")
Kotlin fun main(args: Array<String>) {
println("Hello, world!")
}Minor nit: the sort example needlessly uses two lines for the Swift version.
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 * 1000Are 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?
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.
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 ...
}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...
"0..<count" instantly tells me that it's not including value, and follows the matematical interval notification [0..count] vs [0..count)
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 0 ..< count
I think Swift programmers should adopt this style.When I see "0..<n" I know the range is exclusive of n.
Also, exclusivity is almost always what you want, so "0..n" should just default to exclusivity and "0...n" could be inclusive.
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.
Also, inclusive doesn't allow you to specify empty ranges. That may mean having to add if statements to your code, making it uglier.
I would prefer using notations [m,n) and [m,n], even though that uses a notation used in mathematics for a set to specify a sequence.
Of course, one would want (m,n) and (m,n], too, then, but that first one probably would make parsing your language difficult.
Another benefit: creating a series of right-exclusive ranges from a sequence [a, b, c, f] is easy: [a, b) [b, c) [c, f)
http://stackoverflow.com/questions/9690801/difference-betwee...
I always remembered it as "the third dot makes it bigger so it pushes the range and the last item falls off". I can't remember where that came from, perhaps related to the poignant guide:
http://poignant.guide/book/chapter-3.html#section2
I actually find in practice the swift ranges are the only ones I can reliably use without having to stop and look up the reference syntax every time.
For some reason, for me, `0..<n` reads as "0 through less than n" which signals to my brain a clear signal of an exclusive range.
Then I can work from there and if it doesn't have the < symbol it must be exclusive.
I suspect `0..=n` would work similarly well, but I've not seen a real language to ever do that yet
This could be extended to cover `0=..=n`, `0<..=n`, `0<..<n` and `0<..=n`.
You can actually define that syntax in Haskell:
Prelude> let a =..= b = [a..b]
Prelude> let a <..= b = [(a+1)..b]
Prelude> let a <..< b = [(a+1)..(b-1)]
Prelude> let a =..< b = [a..(b-1)]
Prelude> (1 =..= 4, 1 <..= 4, 1 <..< 4, 1 =..< 4)
([1,2,3,4],[2,3,4],[2,3],[1,2,3]) count.forEach {
// do things
}How's that different from:
for (int i=0; i<=count; i++)
in e.g. C99?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.
OTOH, a "loop .. for .. {upto, below} count" leaves less questions in a casual code review :)
scala> 1 to 3
scala.collection.immutable.Range.Inclusive = Range(1, 2, 3)
scala> 1 until 3
scala.collection.immutable.Range = Range(1, 2)
> 1 through 3
# [1, 2, 3]
> 1 until 3 # or 1 to 3
# [1, 2]
as explicit word range notation?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/go...
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).
see:
The kickstarter apps are open source so you can compare it yourself.
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?
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.
val oneInch = 2.54.mm println("One inch is $oneInch.cm() centimeters")
println("foo ${oneInch.cm()} bar")
println("fez $quux")I presume Kotlin also traps out-of-range array accesses.
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.
What I do now is use j2objc, but here I am stuck in Java land.
(Not updated recently.)
* 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 */
}[0] 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
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.
greet(name: "Bob", day:"Thursday")
but with _ you can call greet("Bob", "Thursday")Swift forces you to use named parameters if you don't do that.
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. func greet(greeting: String, personName: String) {
print("\(greeting), \(personName)!")
} -(void) greetWith:(NSString *)greeting to:(NSString *)personName
and you'd call it like [self greetWith:@"Hello" to:@"Bob"]
Swift's external/internal parameters are built to allow the same style as was used with Objective-C and easy bridging. Swift's APIs tend to be terser than Objective-C ones, though.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. 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.Most definitely yes. In fact it used to be that the first parameter was implicitly positional (in Swift 2 IIRC), this was removed to make all parameters named by default.
And do note that you can provide a single label for a parameter, it will be used as both "internal" and "external" names:
func foo(bar: String) {
print(bar);
}
foo(bar: "3")
func baz(qux quux: String) {
print(quux);
}
baz(qux: "4")
> and is using different external names so commonAlso yes, it's absolutely ubiquitous, if only because that's the one way to provide "positional" parameter.
For the first versions of Swift, they actually had two versions. For functions (i.e not functions inside classes), you didn't have to have named arguments for the first parameter, but you did for methods (functions inside classes).
They explicitly added it for Swift 3 to make it more consistent with method.
I think I like the consistency more, but I do agree "_" is ugly. I don't have an idea of what else they could do though. I don't want Swift to make the parameter names optional, since no one would use it (like in Python, I rarely see named arguments being used)
On a side note, I like the _, it's a clear signal of not caring about something and doesn't take up a lot of visual space.
I think argument labels are great, makes the code much more readable.
func sayHi(to personName: String) {
print("Hi \(personName)")
}
sayHi(to: "Bob") // Hi Bob
Similarly, using just one label in the function declaration means that they have the same name externally as well as internally.In this case the example is saying that they don't want any external labels.
edit: damnit, beaten
Pedantically it would be much less, even none at all, offensive, since nobody will care whether a programming language's name is not written in Cyrillic, since the latin alphabet is the default for such names anyway.
It's worth remembering that different names have different connotations to different people. And that different things may have the same name. If you are trying to market something you obviously have to keep in mind the connotation to the name to the target demographic. And if someone outside your target demographic complains about the name you probably don't care. On the other hand, in the land of open source those connotations are meaningless. Creators of open source tools don't really rely on marketing.
Well, except if you are an Ukrainian of Russian descent and root for the (ex)home team...
Most of ethnic Russians in Ukraine signed for the
Ukrainian army, fighting against Putin’s invasion,
against the same Russians that came from the other side.
(from http://marginalrevolution.com/marginalrevolution/2017/05/con.... Note the source is Kasparov, who is not an entirely unbiased source where Russia is concerned ;))To say the least...
It was the constitution/law that held US together as a nation instead of a shared history/culture (well, except WASP culture, which is on the wane).
With regards to the potential politics of naming things I think it's a tricky thing. When a brand has been established it's already too late and what started as "Naming something after a Russian island" ends up being problematic.
We're too global in software development to release a brand renamed in certain regions to solve this the traditional way, so libraries and languages have to be extra careful when dealing with naming.
Honestly, though, I would think we could all get past it by considering that maybe names are just names and we should be above the politics.
Without explicitly naming them, once you get into the realm of Stalinism or the holocaust, surely it wouldn't take too much imagination to come up with a few names too unsavoury even for you?
I'm sure you could find a name that if not met with indifference or a laugh would elicit from me an eyeroll or a statement like "come on, that's dumb" or maybe "that's just asking to derail conversations" but I don't think you could 'trigger' me into a fit. (Of course you're welcome to try via email.) It's just a name.
I can see a problem if you expect to pay that cost frequently when you bring up the word, and thus avoiding it, but if that's really the case it's worth wondering what other sorts of issues will come up that you don't expect when deciding to take the chance of alienation cost. If I made something as awesome as Stalin I'd put it on my resume, even if it resulted in periodic emails/comments about how insensitive a name it is. Even if some tech readers won't want to work with me because of it, I wouldn't want to work with them, so we're both happy, and we find that out before we actually try working together. I wouldn't put a 'I made Stalin' bumper sticker on my vehicle though. For a name like Kotlin, I really doubt Ukrainian programmers would be upset over it, it seems so absurd, but I can see the possible issue of the general public being sensitive about it in which case it's wise to only have the association in tech contexts.
Pretty sure we're already at that point, for some industries/professions. Anything in tertiary education, certainly.
Obviously the names are tongue in cheek jabs. There's no language called Auschwitz, afaik, and even if there was, it would have as much right to exist as Java or Python or whatever.
You don't get to tell people what to name things just because you're offended. You get to be offended, that's it.
Sure you do, and you get to say your reasons too, refuse to adopt something based on those reasons and try to persuade other people and organizations to accept your reasons. You even get to apply mild sanctions - like not buying things from them or discouraging others from interacting with the person who did the thing that offended you.
You just don't get to forcibly compel anyone. If they disagree with your reasons and don't care about upsetting you, you can't make them change.
It seems that a lot of people want not just freedom to offend with their speech, but also freedom from the reasonable consequences of offending (including responding speech), which is even less coherent than wanting freedom from offensive speech.
Your freedom to say what you want doesn't come with freedom from the consequences of saying it.
It's reasonable to distance yourself from a bad name, just as many people have chosen to rename things that were named Isis.
just for curiosity, do you still have access to Internet and https://github.com/jetbrains/kotlin? I have heard that social networks and many other services in Ukraine are prohibited by the government (after prohibiting other media like TV and newspaper) and now people are installing VPN and other tools by using experience of China to overcome these obstacles. Is it so?
That's what most totalitarian states say when they limit the access to the information.
> Imagine half of all Ukrainians communicating via a social network that is fully controlled by the enemy
Oh, yeah, I see now. You were being sarcastic, isn't it?
This sounds really stupid, considering that many Ukrainian programmers are already using JetBrains products and that punishing a great company for the actions of politicians is kind of sad.
Any multinational company needs to do their research before deciding on a name.
It's not though, and there are many cultures in the world where people are so far removed from what happened that they don't have an understanding of why people would be upset about it. See:
http://kotaku.com/man-opens-nazi-cafe-baffled-that-it-pisses...
https://en.wikipedia.org/wiki/Cross_Cafe
Plus numerous other examples
I think I wouldn't necessarily put that I use Hitler on my CV, due to the negative feedback I would receive from others not in the field.
But on the other hand, barely anyone in the United States has even heard of the island Kotlin, so I'd feel more comfortable doing that.
But Kotlin IS NOT equivalent to Hitler AT ALL, Kotlin is like if you named your programming language "Texas" and somebody objected to the name, because "there are defence contractors located in Texas".
That doesn't quite work—Pearl Harbor was a US base, so most Americans would be okay with it. The negative associations we have with it are what was done to it & the people who served there. We're not angry or upset about the base itself.
Wayland: I think it's the name of some America place. Should afghans, syrians, viets, [put whatever country the US invaded] stick to X11 because of this?
I know nothing of Kotlin's specific name associations, but I don't think "it's the name of a place, therefore its fine" is valid in general. I think "Sandy Hook" would be an inappropriate name right now, while "Wayland" is fine, despite both being towns in the same general region of the world: one name invokes something specific in peoples minds and the other does not.
Its sort of like how its generally not a good idea to be named "Isis" right now, despite having plenty of harmless associations unrelated to ISIS. You might be named after the Egyption god but you are still invoking an association that you don't really want to:
https://en.wikipedia.org/wiki/Name_changes_due_to_the_Islami...
I have a friend who's called, quite lovingly so, Hitler in our circle. The nick has nothing to do with any of his beliefs or opinions (we wouldn't be friends if it did). The icing on the cake is my kids talking about "uncle Hitler", that's just laugh-your-way-to-coma material.
two (Wikipedia): https://en.wikipedia.org/wiki/Stepan_Bandera
If you want to piss off a clinical... eww, not a russian, but a post-soviet russian-speaking citizen of Russian Federation (with a little putin in his head), you may place a Stepan Bandera photo on your userpic and name youself as ukrainian nationalist.
If you want to piss off a real ukrainian nationalist, you may use a Stalin phono, or any other communist leaders.
From the point of sight of normal people, both of these sides is braindead. "A plague on both your houses".
In fact, ukrainians don't give a damn about few nationalists like this for whom it "hurts" and will never consider an origin of the language name, not to mention that idiotic [island name - country name - evil status] associativity. Most people in the world are sane, please don't get tricked into internet-bs easily.
If you haven't seen it, go watch the episode from the TV animated Dilbert show, "The Name" - http://www.dailymotion.com/video/x1afila_dilbert-s01e01-the-...
I am a pro-Ukrainian Russian, and I know many Jetbrains employees, who are cool and bunch of hackers and totally apolitical. Don't worry, it is kosher. :)
It has nothing to do with military bases. Just a memorable, concise name which sounds good in many languages.
Unfortunately Apple's ambition on swift seems to have stalled.