It's a totally valid option in some languages and for some semantics. It's among Kotlin's official idioms, for example.
Cleaner syntax with less baggage, quirks, and boilerplate. There are plenty of articles around contrasting the two. The official site is a good place to start.
There was a number of reasons, among which is the ability to create functions that look like custom language constructs, this way we have synchronized
as a function, and not a built-in keyword:
synchronized(lock) {
// do something
}
or with
:
with(foo) {
print(propOfFoo)
funOfFoo()
}
It also enables type-safe builders
You can write it like this:
jdbcClient.update(sql) { queryResult ->
if(queryResult.failed()) {
}
}
In Kotlin, there is a convention that if the last parameter of a function accepts a function, a lambda expression that is passed as the corresponding argument can be placed outside the parentheses.
If the lambda is the only argument to that call, the parentheses can be omitted entirely.
The variable-declaration style shown in this article is this:
val x : Int
This is not the officially recommended style. The following is recommended:
val x: Int
Edit: After I posted this comment, the page was updated to match the recommended style.
To those wondering what makes this official (I was wondering myself), but apparently it's the official guide by Google, hosted on the Android Github account and currently maintained by Jake Wharton (repo).
Haven't yet had a chance yet to compare them, but I'm curious whether it's consistent with https://github.com/yole/kotlin-style-guide and https://kotlinlang.org/docs/reference/coding-conventions.html.
In Java objects can be null, but it's easy to forget the check to see if it's null. In Kotlin this mindset is created for you. You have nullables or non-nullables. The non-nullables can never ever be null. The nullables can be null. You can't simply call a function on a nullable. You have to check it it's null first or use the safe call ("variable?. function" the '?' checks if it's null first before executing the function). So this way you are forced to handle null. For more information you can check the website of Kotlin: https://kotlinlang.org/docs/reference/null-safety.html
Multiplatform docs here: https://kotlinlang.org/docs/reference/multiplatform.html
Example from the docs:
// Common module
package org.jetbrains.foo
expect class Foo(bar: String) { fun frob() }
fun main(args: Array<String>) { Foo("Hello").frob() }
// JVM module
package org.jetbrains.foo
actual class Foo actual constructor(val bar: String) { actual fun frob() { println("Frobbing the $bar") } }
I brought up how I thought the expect
and actual
keywords (but primarily the latter) added unneeded verbosity in the Kotlin Slack awhile back and was pretty much shrugged off (to be clear: not by JetBrains, but others there), despite folks on the Kotlin team admitting that they exist in part to make the IDE's job easier, but weren't actually necessary.
It leaves a sour taste in my mouth, but I suppose it might be because I'm familiar with projects in C/C++ where, if a symbol goes undefined, the compiler/linker is smart enough to tell you that without being hand-held.
I should add that I use Kotlin day-to-day and am generally very pleased with the work JetBrains has done. In this instance, however, I don't see the justification for cluttering the language.
A few examples of the Kotlin documentation addressing issues explained in the book:
https://kotlinlang.org/docs/reference/exceptions.html https://kotlinlang.org/docs/reference/java-interop.html https://kotlinlang.org/docs/reference/generics.html
For people like me, that don't like "look, I've read the documentation and write many words" articles:
In Kotlin combination of default arguments and named arguments in class constructor can replace plain old "builder" pattern.
Do you mean like if a variable starts with _ it's automatically made private? Honestly I'd just stick with the Kotlin style guide which is pretty sane.
Personal coding styles are going away with the advent of gofmt, prettier, black, etc. It's really quite freeing and a big help on teams. Not as big of an issue for a single coder.
Here's an official list of comparisons
As for an ELI5, kotlin allows for the usage of Java 8 features that would otherwise be incompatible on earlier versions of Android (or would require 3rd-party libraries like Retrolambda). Also, it's less verbose and on average would end up with less code than if you wrote the same thing in Java.
I would guess this has to do with using it inside of a ViewHolder. Most likely using the synthetic views in an activity or fragment is fine.
From my understanding they had it set-up incorrectly to begin with (which is why they are changing it). To use the synthetic properties in a ViewHolder correctly you are supposed to have it implement a LayoutContainer interface as well as turn on the experimental flag. The synthetic property is more than just a shorthand for findViewById. It handles caching it for future usage. If it doesn't know when to release this view it could potentially leak some memory (which is what this is most likely fixing).
More information: https://kotlinlang.org/docs/tutorials/android-plugin.html#layoutcontainer-support
Yes, as others have said, you do get primitives in Kotlin, but it's perhaps a little more opaque than you're used to. It's worth looking at the Kotlin docs on the matter, but the tldr is
> "On the Java platform, numbers are physically stored as JVM primitive types, unless we need a nullable number reference (e.g. Int?) or generics are involved. In the latter cases numbers are boxed."
So it's mostly left to the compiler to do the right thing, but admittedly it can be a little challenging to ensure you don't accidentally force boxing unless you're fairly diligent.
They're othogonal concerns.
Coroutines are used for more than just "lightweight threads". Ever use <code>buildSequence</code> (now just <code>sequence</code>)?
A coroutine is a chunk of code than can voluntarily suspend itself. That's great for sequence generation because it resolves the impedance mismatch between pull-based sequences and push-based generation code. It's also good for async code, since every async operation entails that the current "computation" be suspended.
Coroutines are useful in places where threads would cause problems - typically when you would have so many threads that they would put undue pressure (memory, scheduling, etc.) on the JVM. Async is one example, as are actors.
I have a Kotlin application that had been using threads, though not very many threads and most of them are sleeping most of the time. I had tried porting it over to the experimental coroutines, and specifically to kotlinx.coroutines. It worked. But (at least in IntelliJ 2018.2.4 and the 1.2.71 version of the plugin), things weren't as nice as with explicit threads. Stack traces were less intelligible, and breakpoints didn't work quite right. In the end, I realized that we weren't really gaining anything from using coroutines, so I switched back.
One thing that I might keep, and even try to polish up a bit more, was some code that I had written that used coroutines to automatically perform "tail calls" even in non-tail positions (there are some API challenges, but I think I can resolve them, especially now that Kotlin supports callable references to suspend fun
s). But again, that doesn't really have anything to do with threading.
let
here is a function, not a language keyword.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/let.html
You can just use regular if statement and Kotlin compiler will automatically know that inside the if(doge != null)
block, doge is not null, and that in the else block, it's null.
var doge: String? = null;
if (doge != null) { // you can safely dereference doge here; the compiler knows it's not null println("wow"); println("such doge"); println(doge) } else { println("not wow"); println("no doge"); }
He's asking specifically about Kotlin Native, which has nothing to do with the JVM.
Deeper Meaning Explainer ™
In Kotlin, !!
is an operator that will throw an NPE when applied to a null variable.
It is there just so we can still have NPEs in Kotlin if we want.
You can introduce a type parameter with some generic constraints, like this:
fun <T> a(val b: T): Unit where T : UpperLevelStandardClass, T : myInterface { .... }
It's documented at the bottom of this page: https://kotlinlang.org/docs/reference/generics.html
"Using underscore for naming the mutable state holder"
Well, this is exactly why underscore was introduced in Kotlin CodeStyle https://kotlinlang.org/docs/coding-conventions.html#names-for-backing-properties
The right part of the when
branch needs to be a single expression. The compiler thinks the println
is part of the next branch (that's where the incompatible type comes from - it's expecting a boolean for the branch).
The solution is to use blocks, i.e. wrap the two lines in curly braces, as described in the docs.
Funny how they chose that generic functions should have their type parameters declared before the function name, while when the function is called you pass the type arguments after the name.
It kind of make sense in Java to (always) put the type params/args before the name because it would be weird to have public T foo<T>();
(type T
would appear before being declared).
In Scala, you have the type params/args after the function name in both declaration and call, which works fine because the return type is specified at the end.
So why that inconsistency in Kotlin? They could do it consistently like in Java or like in Scala.
This is BTW not Kotlin's but Gson's fault. Gson does not know how to create data classes, and uses black magic to construct them with sun.misc.Unsafe
calls. This skips all Kotlin's safeguards, creating essentially an object that should be impossible to exist in the JVM (that's why it's called "unsafe").
You should feel bad if you use Gson with data classes, and you are guaranteed to shoot yourself in the foot sooner or later. Use Moshi or native Kotlin serialization instead.
Those guides are most likely for pre-1.3.0 coroutines, where that was allowed. The coroutines available in 1.3.0 make a push towards structured concurrency, where every coroutine has a scope and when that scope ends it can be cancelled. To launch a coroutine like you would pre-1.3.0, use <code>GlobalScope.launch {}</code> instead.
I think it's terrible and there is zero reason to write it like that except to be a smartass. I would definitely prefer
if ($email !== null) { $this->setEmail($email); } // On a single line ...
But then I would also not initialize properties with setter functions like that, and also, if $email
really is optional,
why can't I just call setEmail(null)
anyway? But of course, example code, etc.
Slightly unrelated:
In an ideal world, I would also like if
to be an expression like in Kotlin (https://kotlinlang.org/docs/reference/control-flow.html), but we have to work with the language limitations we have. Abusing the short-circuiting of operators like this often suggests a missing language feature.
This is documented here:
https://kotlinlang.org/docs/reference/null-safety.html
> An uninitialised this available in a constructor is passed and used somewhere ("leaking this");
There would be 2 solutions to this:
this
to other functions in contructors to avoid leaking the uninitialised this
objectThe first solution would be pretty restrictive and cause a lot more trouble than is solved. The second solution would probably be pretty hard to implement (and impossible in the general case), lead to longer compilation times and to strange compilation errors after small changes because the compiler isn't able to prove the safety of the calls anymore. Some perfectly safe code would probably not be compilable because the compiler wouldn't be smart enough.
Plus there might be interoperability issues with java. Having limited null safety in the constructor is a pragmatic solution, and causes little problems in the real world.
It's part of compilation.
It's not just an IDE warning, but literally you can't compile if you try to pass null to a parameter that isn't nullable for instance.
Just check it out in the docs.
You have a range of optional<T>
s. You flat-map it and now you have a range of the contents of all of the engaged optionals.
For example, you have a bunch of things you want to try to parse, and you need to continue with the results of all the ones that are parsed successfully.
Edit: This is basically what Kotlin's <code>filterNotNull</code> is. Rather than container semantics, it treats its form of optionals (i.e., nullable types) specially in the library.
I've never understood this, neither in Scala nor in Kotlin or any other language:
val text = """ |First Line |Second Line |Third Line """.trimMargin()
If you need a stupid margin (that you're removing at runtime, instead of at compile time!) in order to get indentation right both inside the string and in the "host language", you're losing most of the benefits of multi line strings.
Sidenote: I've learned there's a better way: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/trim-indent.html. Still done at runtime (and probably with an even larger overhead), but at least not with this stupid |
character messing everything up.
Delegated properties, nullable types, type inference, (limited) reified types, extension functions, extension lambdas, and optional parameters :-D
To get started just check out the docs for those terms at kotlinlang.org -- here's the article for delegated properties: https://kotlinlang.org/docs/reference/delegated-properties.html
I think people should be more thoughtful as to what class they are adding the extension methods to. In the case of the Picasso example, it would make more sense to create the extension to ImageView
instead of Context
i.e.
fun ImageView.loadImageCenterCrop(url: String) { Picasso.withContext(this.context) .load(url) .centerCrop() .fit() .into(this) }
Usage:
mImageView.loadImageCenterCrop(url)
Also, I don't see what is wrong with creating extensions that are utility methods since they were meant to be just that.
https://kotlinlang.org/docs/reference/extensions.html#motivation
Ah, I'm not 100% sure but this may be a case of smart casting. You may have found a weird edge case. (If Kotlin knows for sure your value is, say, a String, then it auto casts for you, for example)
You want xor (exclusive or).
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/xor.html
Edit: for the second request you already have syntactic sugar if you're willing to incure an allocation
if (thingOne in listOf(thing2, thing3))
You probably know that the collections in kotlin are not immutable, the collections by default are read only. Probably this stackoverflow question will help you understand the differences between the types of collections.
So, when to use them? Kotlin offers a great type of methods for this type of collections, that is a point in favor. Another question is why we always use, in other languages, mutable type collections when we do not take advantage of them as we should. For example, imagine that I want to obtain data from an API and save the information in a list, this data is only obtained and displayed, it does not make sense to use a mutable table, since it will not be edited, it will be read only.
Kotlin official docs give you a better idea of what I mean.
I hope I have helped. Greets and keep coding.
Kotlin, just like any other language these days, has a perfectly good beginner's guide, a tutorial, documentation, and basically everything else you ever need to get into the language on its fucking website.
Fuck off, blogspam.
I don't know the specific reason they went with arrayOf(…)
instead of supporting a native syntax using […]
(same for mapOf( key to value)
), but I do know that one of the reasons is those aren't special language constructs—they are just top-level functions.
A lot of Kotlin seems to follow this mindset, that it's better to use top level functions and the built-in type checker, rather than adding language extensions.
One awesome side effect of this is you can, effectively, create your own extensions that act exactly as the "native" functions. in the mapOf
example above, the <code>to</code> itself is just an infix function.
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)
It's literally that simple, and now you have something that works very much like a language-level construct, but is actually just a method call.
Small thing that might be useful: if you use coroutines in your SDK, you can give them names that indicate they were launched by your SDK https://kotlinlang.org/docs/coroutine-context-and-dispatchers.html#naming-coroutines-for-debugging. This would make it obvious to users debugging their app which coroutines were launched by your SDK.
For some tutorials please take a look at https://kotlinlang.org/docs/tutorials/native/basic-kotlin-native-app.html and others. Regarding Android+iOS development take a look at https://github.com/JetBrains/kotlin-mpp-example
Yes, the Kotlin/Native compiler is a frontend for LLVM https://en.m.wikipedia.org/wiki/LLVM
The targets can be specified through the Kotlin/Native gradle plugin konan for example https://kotlinlang.org/docs/tutorials/native/gradle-for-kotlin-native.html
To add to this, Kotlin is fairly easy to start learning. I'd wager that most Java developers can pick up the basics in an hour or two. An excellent place to begin is Koans, a tutorial set which starts at 'Hello World' and guides you through the major language features.
Inferring from your question that you actually want a substring until the first line feed or the whole string otherwise, you can take a look at this function:
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/substring-before.html
val sub = someString.substringBefore('\n')
They do support 1.8 bytecode if you want it, but few JVM languages strictly require JVM 7 or higher bytecode compatibility simply to work, if the language can compile down to operators with the same effects without extra keywords. And I sincerely don't believe they target 1.6 because of Android, but rather because 1.6 is a common JRE runtime that enterprise development still uses (1.5 not so much, and anyone past 1.6 is probably on 1.8)
There's a fairly lengthy discussion in the docs about when Kotlin doesn't perform implicit casts. Due the reasons outlined there, I doubt you'll find a way to implicitly convert primitives, because it can lead to unexpected errors.
While Kotlin is designed to reduce boilerplate, it's primary goal is safer code. Forcing the developer to be aware of type conversions like this is a good example of where safety was chosen over being terse.
Hopefully someone with more experience can help further. You may get more help if you included specific types for the original example. It's hard to infer what you are converting from with the examples there, and which libraries you are using.
The documentation addresses this directly.
> In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.
Note: This page is the first result when you search of "kotlin ternary".
In Kotlin, bitwise operators are implemented as functions. For &=, the function is called and. Go here and ctrl-f for "bitwise and", you will see a list of all the bitwise operators in Kotlin. Hope that helps.
> I take your word for it, as I've read recently different opinions.
About Kotlin's IDE support? In IntelliJ the support for Kotlin is excellent - perhaps not quite as advanced as their Java support, but close to it.
> So is possible from other JVM languages, and, especially, from… Java itself.
Yes from Java itself, and yes languages like Scala can interoperate with Java, but Kotlin really go out of their way to ensure bi-directional interoperability in a way that no other JVM language does.
> I really try to avoid having mutable objects, so I don't see a point in properties.
It's good practice to avoid mutability if you can help it, but sometimes it's necessary. And if you like immutability, you'll love the "copy" method in Kotlin's data classes.
> Still it's null which I prefer to not have at all.
The reason people don't like null is that it causes runtime exceptions. If the type system is protecting you from runtime exceptions then there really isn't any reason to dislike null. Kotlin's approach is equivalent to an Optional or Maybe construct, but without the overhead of a wrapper object.
> Looks great, but it's not their discovery. Home many other languages have you fall in love recently?
Just because a language feature isn't unique doesn't mean it doesn't benefit the language.
> See point 5. > See point 5.
> Which is out of discussion, unfortunately… But I wish you best programming in Kotlin.
If you haven't already you really should take a bit of time to review Kotlin's documentation. It really does have a lot of nice features. Many of them aren't unique to Kotlin, but Kotlin brings them together in a really nice way.
As the comparison page already mentions:
> Taking this into account, if you are happy with Scala, you probably do not need Kotlin
Scala can do everything what Kotlin can and it can do even more. Not to mention that dotc+scala.meta moves another step forward in terms of tooling support. And if we consider that Scala has the libraries Kotlin does not have, there isn't really anything interesting coming from there (at least not for a Scala developer).
Because I think Java is a pre-requisite because you need an understand of the annotations that manipulate what gets generated behind the scenes (@JvmStatic
, @JvmField
, and so on).
See https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html
Once you know what you want to achieve with the Kotlin code you are writing, it helps a lot.
I would still use a different name.
Shadowing does kinda suck, but in practice it's a complete non-issue, because the IDE will show you that ugly yellow box.
Regarding platform types, they do process @NonNull
/@Nullable
annotations at least, if the Java code has them https://kotlinlang.org/docs/reference/java-interop.html#nullability-annotations.
I would interpret it as a "redundant" construct which should be avoided.
> In general, if a certain syntactic construction in Kotlin is optional and highlighted by the IDE as redundant, you should omit it in your code. Do not leave unnecessary syntactic elements in code just "for clarity".
https://kotlinlang.org/docs/reference/coding-conventions.html#avoiding-redundant-constructs
Kotlin has amazing 'extensions' plugin to access Android views in standard XMLs. https://kotlinlang.org/docs/tutorials/android-plugin.html
I highly suggest to start from official approach to Android layouts. And later on you can try different frameworks and tools. This way you will have more tutorials, examples and official tools (like layout preview and wysiwyg)
Methods coming from Java code (JavaFX for example) are treated in a special way because there is no way to deduce the nullability of its arguments and return values.
Keep in mind I'm coming from the perspective of evaluating the organization and cleanliness of the code itself, not its capabilities in a data science context. I assume there's a reason so many data science types like R. That said, python is also incredibly popular among data scientists, and it's much nicer as an actual programming language. Pandas, NumPy and SciPy are all very popular python libraries that data scientists work with day in and day out.
As an idealist, I would say learn Kotlin and be in the vanguard of the revolution. But as practical advice for your career I would say learn python.
I can't test this right now but it sounds like a problem with line endings. Odds are you're on windows, so by default a newline isn't just "\n"
, it's "\r\n"
. "\r"
moves the "cursor" back to the beginning of the line being written to.
When you split on "\n"
, it leaves behind the "\r"
character. All of the odd behaviors you're seeing can be explained by this stray "\r"
. The reason "Ice Cream"
is the only one that works consistently is because you likely don't have a newline at the end of your file.
To remedy this, either change your line endings, or trim each string in foodList
.
If you're just starting out, learn Kotlin. I found this a great tool: https://kotlinlang.org/docs/tutorials/koans.html
Make sure to check out the developer guides
I've always found vogella a good source for tutorials.
Start with something small, a Todo list or something. Start by making it runtime only persistent and work your way down to database persistence, firebase persistence and just keep at it.
You can achieve this by usng when
and also introducing the <code>is</code> keyword and smart casts.
when(person) {
...
is Student && person.studentName == "Richard" => "Still here Ricky?"
is Student && person.studentName == "Foo" => "Hey, ${person.studentName}."
...
This is a very superficial feature comparison. You're missing all of their differences: https://kotlinlang.org/docs/reference/comparison-to-scala.html
Also, not explained is the core language goals behind each one. Scala is the C++ of JVM languages. It's everything and the kitchen sink. It wins out on features but nobody understands what's going on when they use it. Kotlin is just what Java should have been if Java didn't insist on perfect backwards compatibility.
Tried it for 10 minutes and literally all sites I tried didn't work. For example, in this site
https://kotlinlang.org/docs/reference/classes.html
you cannot expand the menu entries (Basics, Functions and lambdas). I enabled JS, though.
Too bad, I'm looking for a lightweight chrome/firefox alternative to save some RAM.
Kotlin is also compiled to java bytecode so type erasure is still a thing. Not taking into account MultiPlatform Compilation because I don't know about that part.
https://kotlinlang.org/docs/reference/generics.html#type-erasure
!!
really should not be used except in extraordinary circumstances - it looks ugly and out of place on purpose. It's the equivalent of Optional.get()
- it is breaking Kotlin's null safety.
I agree that seeing Kotlin programmers using it would be distressing. The documentation describes it as "for NPE-lovers".
https://kotlinlang.org/docs/reference/operator-overloading.html#assignments
lays it out fairly plainly that they do it completely intentionally. The confusing part is why this doesn't happen with just a mutableList, ie
val test3 = mutableListOf<String>("one") test3 += "two"
is not subject to that rule.
The large problem is probably that your statement can validly go to two different forms, and there is not a precedence for index operations. x[1] += 1 is confusing because it can be
x.set(1, x.get(1) + 1)
or
x.get(1).plusAssign(1)
Some info is available here:
https://kotlinlang.org/docs/reference/java-interop.html#mapped-types
These talks has some relevant info:
You have two options in Kotlin.
You probably want to learn the general kotlin constructs first and apply them to android app development afterwards. Kotlin koans is a great guided way to start.
I feel the same here :P I used _
because that's what official Kotlin docs suggest for backing properties, but personally I also don't like it :d
Predefining variables makes things less implicit. If you declare a String. Should the default value be "" or null? It's pretty annoying to have to think about that.
You mentioned in arrays. Arrays are just lists, they are ordered collections of elements. Look at any other modern programming language and they all converge on the concept of a list. So why worry about arrays when you could abstract away all those details and use a list. You can do anything you want with arrays using lists in kotlin and be more elegant with it (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)
You say you don't want to use optionals(?
). The problem is that every object in Java is optional. Every object can possibly be null and you have to consider the possibility that an object is in fact null everywhere. In java, you have to be paranoid about NullPointerException. It's the most common cause of crashes in my experience. Explicit optionals(?) help.
I don't use Kotlin but this page states that Kotlin can compile down to JVM bytecode.
Edit: swapped my link out with one that points to the official Kotlin FAQ. Previous one was a link to Stack Overflow, which isn't the most authoritative website.
This is simply not true: Scala keywords: 40, Kotlin keywords: 87 (yes, you have to count soft keywords as well). Scala operators: 10, Kotlin operators: 34. See https://www.scala-lang.org/files/archive/spec/2.11/01-lexical-syntax.html https://kotlinlang.org/docs/reference/keyword-reference.html
Typically it is used for RecyclerView ViewHolders but I think you should always make the nested inner class static unless you have a really good reason to.
This doesn't happen for view holders but I see plenty of spaghetti code because someone in an inner class decided to use a field/value from the outer class. This makes it really hard to keep these classes manageable since they're "reaching" across and grabbing things that they shouldn't.
I try to make my dependencies as explicit as I can. (through the constructor)
basically same question on Stack overflow: https://softwareengineering.stackexchange.com/questions/238782/why-prefer-non-static-inner-classes-over-static-ones
I really like that Kotlin made inner classes explicit by adding the "inner" keyword so hopefully devs think about whether or not the class needs to be an inner class. https://kotlinlang.org/docs/reference/nested-classes.html
tl;dr: inner classes have references to the outer class and its members. Does the inner class need access to some members ? Maybe, but it probably doesn't need access to everything that belongs to the outer class so I tend to make those dependencies explicit (constructor/di/etc)
BTW, the language reference does a pretty good job at giving a high level view of all the useful concepts in the language. Also, while you are still learning, you can write Java code (presuming you are a grumpy Java developer) and run the "Code > Convert Java to Kotlin" action, which usually produced a decent first pass at Kotlin.
Good luck!
?. is a null check. So you can do view?.animate() and if view is null, nothing will happen. No need to do if(view != null) view.animate()
?: is the "elvis" operator, which is "if this is null, do this instead, eg: val someString = getAString() ?: "couldn't get string"
More: https://kotlinlang.org/docs/reference/null-safety.html
Try to be less sensitive to Reddit voting, people are rarely rewarded for complaining about downvotes. Even with a vote of 0 plenty of people will still see your work.
Also you got 22 votes when you posted this library just 5 days ago, so people may have felt that this post was repetitive.
Is there any way you can use tailrec to make your function more efficient?
Extensions must be imported into the file that wants to use them, so they aren't global or otherwise hidden.
Also, similar to what /u/cilph said, you really should be using an editor that allows you to jump to function definitions, no matter what the language.
Delegated properties are already supported in 1.0; you can read about them here: https://kotlinlang.org/docs/reference/delegated-properties.html
The new feature in 1.1 is declaring local variables as delegated properties.
Other than the reasons people have explained (concise syntax, lambdas, etc) Jet Brains maintains an Android library that extends your bread and butter classes like Activity and have added a ton of useful properties.
In Kotlin, the asynchronous function calls are sequential by default. If you want to make the execution asequential, you have to explicitly state it.
The reason behind that design is that in vast majority of the asynchronous functions, the flow is sequential, i.e. you await an asynchronous function before calling another one. Therefore they made it the default behavior.
Here is a piece of documentation regarding this issue: https://kotlinlang.org/docs/composing-suspending-functions.html
Java was and is verbose, Kotlin tried to suppress that and succeeded that goal in some ways but also introduced new ways to make code more verbose but I think type alias is your friend and can reduce verbosity.
Mind you, this is Kotlin code. The === operator in kotlin works like the == operator in Java and checks for referential equality. I'd argue that it's unnecessary in this case because of the way that enums work in Kotlin, but it's valid code nonetheless. Actually, in this case it shouldn't matter which of the two operators you use.
Kotlin is more concise than Java, interoperable with Java, has built in safety measures(helps you get rid of NullPointerExceptions) and this tutorial
In that particular case, widening an Int to a Float is a lossy widening. At the upper end of the range, there are Ints that can't be perfectly represented by Floats. When promoting such an Int, you would get a meaningfully different Float.
In the general case, I don't know. Some promotions are safe. I guess they are going for consistency.
> why not add something like the custom add operation methods, but for converting
I don't know what you mean. Things like +
work by essentially having a bunch of overloads. You could do the same thing. If you want your function to also accepts Ints, create an overload. You'll quickly run into combinatorial explosion (what happens if they pass an Int and a Float, or pass a Float and an Int?).
You can annotate Java methods to be explicit about whether or not they return null
. The Kotlin compiler will pick up on the annotations
See: https://kotlinlang.org/docs/reference/java-interop.html#nullability-annotations
There are so many reasons that argument falls down.
Firstly, if you leave the company as the only Kotlin developer, then any time someone wants to make a change to your code, then they have to spend a day (but likely more due to teething troubles) learning Kotlin to even make small changes or fixes. That fix may be needed ASAP, without the realisation that some developer has gone rogue and written components in a different language without the agreement of their team or manager.
Secondly, If you use any advanced features of Kotlin that Java doesn't have, that does not translate directly to java and the developers won't be able to understand the code with "only a day" of training.
Looking at the features here that aren't in java, if you use something like a lambda expression or coroutine, you're really going to trip someone up.
Thirdly, If 100 people have to spend "only a day" learning Kotlin because of one developer, that's 100 man days of work just to continue doing their work. That's expensive.
Finally, arbitrarily throwing a spanner in the works is not a good test of a developer's ability. I would judge a developer's skills according to their architecture, structure, testing, readability, communication, safety, usability, etc. And you can't decide that they're a bad developer just because you've decided to unexpectedly change the codebase for something they've got years of experience committed to muscle memory.
Kind of agree and disagree. "To anyone", not sure with that.
>I have experience with C#, and recently Ive been taking an basic android course with java.
If you can read documentation in Java an understand it and understand the differences between Java and KotlinI think you are good to jump directly into Kotlin.
For loop iteration over ranges
Consider the ff examples where 1 and 4 might come from elsewhere in your program:
Iterate ascending inclusive
for (i in 1..4) print(i) // prints "1234"
Iterate descending inclusive
for (i in 4 downTo 1) print(i) // prints "4321"
there are 2 more ways to do this
Iterate ascending exclusive
for (i in 1 until 4) print(i) // prints "123"
Iterate descending exclusive
for (i in 4 downTo (1+1)) print(i) // prints "432"
there are 2 more ways to do this
Iterate ascending with steps
for (i in 1..4 step 2) print(i) // prints "13"
I like to do code golf challenges to get familiar with a language and when trying challenges such as this one, I encounter this Range hullabaloo. I wish c style for loops was a thing in kotlin for the sake of integral types. Not everything has an iterator
> my understanding is that Kotlin code gets transpiled to Java code before being compiled to bytecode
I do not believe this is the case. Kotlin generates JVM bytecode directly and does not rely on the Java compiler. From the Kotlin FAQ...
What does Kotlin compile down to?
When targeting the JVM, Kotlin produces Java compatible bytecode. When targeting JavaScript, Kotlin transpiles to ES5.1 and generates code which is compatible with module systems including AMD and CommonJS. When targeting native, Kotlin will produce platform-specific code (via LLVM).
Does Kotlin only target Java 6?
No. Kotlin lets you choose between generating Java 6 and Java 8 compatible bytecode. More optimal byte code may be generated for higher versions of the platform.
In principle, yes but in practice it's less severe. See Null Safety and Platform Types.
Before, the Kotlin team tried to infer the nullability of the whole JDK which turned out to not work so well in practice. The current solution is imo a very good and pragmatic choice.
For the record, Kotterknife is nice, but you don't really need it (probably). I think you can do everything it does with Kotlin Android Extensions and they're even easier to use.
It would be absolutely backwards for it to return false. You seem very intent on having your way though, so there's no chance of convincing you. But, let's use the kotlin documentation for this:
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/is-digit.html
val chars = listOf('a', '+', '1') val (digits, notDigits) = chars.partition { it.isDigit() } println(digits) // [1] println(notDigits) // [a, +]
so let's remove the 1
val chars = listOf('a', '+') val (digits, notDigits) = chars.partition { it.isDigit() } println(digits) // [] println(notDigits) // [a, +]
Huh, that's funny. it partitioned an empty list for the things that are digits, isDigit
.
Therefore an empty list of nothing is a list of digits. per the definition of .isDigit()
. Therefore an empty string (you would split it into its constituent chars), is an exact list of digits. You can literally test this with the above code.
I know it's not a tutorial, but Kotlin in Action sounds like it would fit the bill as well. I bought it intending to learn Kotlin without knowing java, but it actually assumes a background in java. It also has hints about how to interop with Java if needed.
Hi! We send stickers to people who do Kotlin talks. You can find more info here https://kotlinlang.org/community/talks.html
Sometimes you can also get stickers at Kotlin-related events, however, all we know that events haven't been an option for the last year...
C# Basic Types Kotlin Basic Types
Notice the differences in the organization of the pages (left menu), the formatting and font, the headers, the clear and concise examples, the verbiage, etc.
> I really want to get into creating android app and all
It's totally reasonable to learn to code by making an Android app. If that's what makes you excited, get to it!
If that's where you want to start, the best place to start (just my opinion, but I've used all the options in question) isn't in JS or Java. It's in Kotlin which is an officially-supported Android dev language and the one that Google does their app development in. It runs on top of Java, but kicks out a lot of what makes Java so dense, while having great integrations with Android and IDEs.
Gradle is fairly well documented at docs.gradle.org. Unlike the Java plugin, the Kotlin Gradle plugin is not part of Gradle but is provided separately by JetBrains, so the documentation for that is on kotlinlang.org.
There's also the Gradle Kotlin DSL which is part of Gradle. It has nothing to do with building Kotlin code, but rather is a way of writing the Gradle build scripts using a Kotlin DSL rather than a Groovy DSL.
Hard to say what is an issue here without seeing the relevant code. All this tells me is that you have a ByteArray property that is either non-nullable or was autocast to non-nullable that you used the !! operator on.
Refer to this page of the kotlin docs if you are struggling with null safety in kotlin.
https://kotlinlang.org/docs/reference/null-safety.html
In the future please post a code snippet so it is easier for others to help!
Reposting my response from the ticket:
I don't think either of these changes are necessary. For the first one, you're proably looking for the xor infix function.
The second one is also very easy to implement as an extension function:
fun <T> T.equalsAny(vararg others: T): Boolean {
for (other in others) {
if (this == other) return true
}
return false
}
Which can be used like so:
val exampleOne = 1
val exampleTwo = 2
val exampleThree = 1
if (exampleOne.equalsAny(exampleTwo, exampleThree)) {
//code
}
See example on the Kotlin playground: https://pl.kotl.in/AH2ej02OQ
You can use the find call, it'll return the first matching value and since you mention you have unique values that should work. The below code will check each HashMap in the list for a matching id value, and on the first match add the name value to selectedItems list.
datalist.find { it["id"] == id }.let { selectedItems.add(it["name"])) }
The leading underscore is convention for backing properties in Kotlin.
>Names for backing properties
>
>If a class has two properties which are conceptually the same but one is part of a public API and another is an implementation detail, use an underscore as the prefix for the name of the private property:
https://kotlinlang.org/docs/reference/coding-conventions.html
Lambdas are pretty much just functions without a name. Where you could use a function, you can just type {inputs -> <code-which-manipulates-the-inputs>}
instead, constructing a lambda expression without having to define a specific function with all the usual bells and whistles.