What Java 8 Stream.collect equivalents are available in the standard Kotlin library?

In Java 8, there is Stream.collect which allows aggregations on collections. In Kotlin, this does not exist in the same way, other than maybe as a collection of extension functions in the stdlib. But it isn’t clear what the equivalences are for different use cases. For example, at the top of the JavaDoc for Collectors […]

Read More

In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them

If I have a nullable type Xyz?, I want to reference it or convert it to a non-nullable type Xyz. What is the idiomatic way of doing so in Kotlin? For example, this code is in error: val something: Xyz? = createPossiblyNullXyz() something.foo() // Error: “Only safe (?.) or non-null asserted (!!.) calls are allowed […]

Read More

Idiomatic way of logging in Kotlin

Kotlin doesn’t have the same notion of static fields as used in Java. In Java, the generally accepted way of doing logging is: public class Foo { private static final Logger LOG = LoggerFactory.getLogger(Foo.class); } Question is what is the idiomatic way of performing logging in Kotlin? Solution In majority of mature Kotlin code, you […]

Read More

Kotlin and new ActivityTestRule : The @Rule must be public

I’m trying to make UI test for my android app in Kotlin. Since the new system using ActivityTestRule, I can’t make it work: it compiles correctly, and at runtime, I get: java.lang.Exception: The @Rule ‘mActivityRule’ must be public. at org.junit.internal.runners.rules.RuleFieldValidator.addError(RuleFieldValidator.java:90) at org.junit.internal.runners.rules.RuleFieldValidator.validatePublic(RuleFieldValidator.java:67) at org.junit.internal.runners.rules.RuleFieldValidator.validateField(RuleFieldValidator.java:55) at org.junit.internal.runners.rules.RuleFieldValidator.validate(RuleFieldValidator.java:50) at org.junit.runners.BlockJUnit4ClassRunner.validateFields(BlockJUnit4ClassRunner.java:170) at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:103) at org.junit.runners.ParentRunner.validate(ParentRunner.java:344) at org.junit.runners.ParentRunner.(ParentRunner.java:74) at […]

Read More

Kotlin Ternary Conditional Operator

What is the equivalent of this expression in Kotlin? a ? b : c This is not a valid code in Kotlin. Solution In Kotlin, if statements are expressions. So the following code is equivalent: if (a) b else c This question was reposted from Stack Overflow

Read More