Kotlin class properties in parathesis and curly parathesis - kotlin

Just reading some Kotlin code and notice that we can define properties either in (...) or in {...}.
class Foo(val name: String = "Yuchen") {
val name2: String = "Zhong"
}
fun main(args: Array<String>) {
val foo = Foo()
println(foo.name)
println(foo.name2)
}
What're their differences and when should we use which?

If you transform kotlin code to java using bytecode decompiler you will get that one.
class InitOrderDemo(val name: String = "Yuchen") {
val name2: String = "Zhong"
}
Decompiled java code:
public final class InitOrderDemo {
#NotNull
private final String name2;
#NotNull
private final String name;
#NotNull
public final String getName2() {
return this.name2;
}
#NotNull
public final String getName() {
return this.name;
}
public InitOrderDemo(#NotNull String name) {
Intrinsics.checkParameterIsNotNull(name, "name");
super();
this.name = name;
this.name2 = "Zhong";
}
....
}
Notice, please, that name argument you can pass through constructor invoke, but name2 couldn't be changed - it's similar to constant here.
So if you want property to be immutable (but not constant for all instances of that class), you will need define it in () - in constructor.

Related

how to make reference type for string enum in kotlin and jacoco coverage testable

Converted a java class into kotlin in Android app, the jacoco coverage starts to show 0 coverage on a compiler generated function, which is not access able. Other ones seem fine in the report.
How to make reference type for string enum in kotlin and jacoco coverage testable
java code:
public final class Message {
private Message() { }
public static class MessageAction {
public static final String OPEN = "open";
public static final String VIEW_ALL = "view_all";
#Retention(RetentionPolicy.SOURCE)
#StringDef({OPEN, VIEW_ALL})
public #interface Action { }
public String mAction;
public MessageAction(#Action String action) {
this.mAction = action;
}
public String getMessageAction() {
return this.mAction;
}
}
}
in kotlin;
import androidx.annotation.StringDef
class Message private constructor() {
class MessageAction(#param:Action var messageAction: String) {
#kotlin.annotation.Retention(AnnotationRetention.SOURCE)
#StringDef(OPEN, VIEW_ALL)
annotation class Action
companion object {
const val OPEN = "open"
const val VIEW_ALL = "view_all"
}
}
}
this is sample of how it is used in java code:
public static void doSomeThing(#Nullable String message, #Message.MessageAction.Action String action) {
...
}
and the test:
#Test
public void test_messageAction() {
String testAction = "open";
Message.MessageAction action = new Message.MessageAction(Message.MessageAction.OPEN);
assertEquals(testAction, action.getMessageAction());
}
the jacoco test coverage result shows 0 covergate on the function setMessageAction(#NotNull String var1) which is in the decompiled java code.
And it is not visible from the code's autocomplete hint.
the kotlin decompiled java code:
public final class Message {
private Message() {
}
#Metadata( ...... )
public static final class MessageAction {
#NotNull
private String messageAction;
#NotNull
public static final String OPEN = "open";
#NotNull
public static final String VIEW_ALL = "view_all";
public static final Message.MessageAction.Companion Companion = new Message.MessageAction.Companion((DefaultConstructorMarker) null);
#NotNull
public final String getMessageAction() {
return this.messageAction;
}
public final void setMessageAction(#NotNull String var1) { //<=== coverage result shows it is not called
Intrinsics.checkNotNullParameter(var1, "<set-?>");
this.messageAction = var1;
}
public MessageAction(#NotNull String messageAction) {
Intrinsics.checkNotNullParameter(messageAction, "messageAction");
super();
this.messageAction = messageAction;
}
#Retention(AnnotationRetention.SOURCE)
#java.lang.annotation.Retention(RetentionPolicy.SOURCE)
#Metadata( ...... )
public #interface Action {
}
#Metadata( ...... )
public static final class Companion {
private Companion() {
}
// $FF: synthetic method
public Companion(DefaultConstructorMarker $constructor_marker) {
this();
}
}
}
}
adding #JvmField resolves it
class MessageAction(#param:Action messageAction: String) {
#kotlin.annotation.Retention(AnnotationRetention.SOURCE)
#StringDef(OPEN, VIEW_ALL, CLEAR, TOUCH3D, PLAY, PAUSE, DISMISSED)
annotation class Action
#JvmField
var messageAction: String = messageAction
companion object {
const val OPEN = "open"
const val VIEW_ALL = "view_all"
}
}

kotlin, what is #param used for before the annotation type

In java class with annotation:
public final class Info {
private Info() {
}
public static class InfoAction {
public static final String OPEN = "open";
public static final String VIEW_ALL = "view_all";
#Retention(RetentionPolicy.SOURCE)
#StringDef({OPEN, VIEW_ALL})
public #interface Action {
}
public String mAction;
public InfoAction(#Action String action) {
this.mAction = action;
}
}
IDE convert to kotlin:
class Info private constructor() {
class InfoAction(#param:Action var infoAction: String) {
#kotlin.annotation.Retention(AnnotationRetention.SOURCE)
#StringDef(OPEN, VIEW_ALL)
annotation class Action
companion object {
const val OPEN = "open"
const val VIEW_ALL = "view_all"
}
}
}
it has #param:Action, but replace with #Action it works as well.
what is this #param here for, and can the #Action be used?
#param is for constructor parameter
detail:
https://kotlinlang.org/docs/annotations.html#annotation-use-site-targets

Jackson: Serialize only 10 Properties out of 100

Jackson by default includes all public getters. But if I have hundreds of getters and I want to serialize just few of them, how can I achieve this?
I don't want to use #JsonIgnore annotation to specify all others hundred properties.
You can use Jackson's views or filters to select the serialization form of your object. Here is an example using the filter which picks up the properties with the given names:
public class JacksonFilter {
#JsonFilter("filter")
public static class Bean {
private final String field1;
private final String field12;
private final String field10;
private final String field100;
public Bean(String field1, String field12, String field10, String field100) {
this.field1 = field1;
this.field12 = field12;
this.field10 = field10;
this.field100 = field100;
}
public String getField1() {
return field1;
}
public String getField12() {
return field12;
}
public String getField10() {
return field10;
}
public String getField100() {
return field100;
}
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
SimpleFilterProvider filters = new SimpleFilterProvider();
filters.addFilter("filter",
SimpleBeanPropertyFilter.serializeAllExcept("field12", "field100"));
mapper.setFilters(filters);
Bean bean = new Bean("A", "B", "C", "D");
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean));
}
}
Output:
{
"field1" : "A",
"field10" : "C"
}

Passing complex navigation parameters with MvvmCross ShowViewModel

My complex type wouldn't pass from Show to Init method even with configured MvxJsonNavigationSerializer as specified here Custom types in Navigation parameters in v3
public class A
{
public string String1 {get;set;}
public string String2 {get;set;}
public B ComplexObject1 {get;set;}
}
public class B
{
public double Double1 {get;set;}
public double Double2 {get;set;}
}
When I pass instance of object A to ShowViewModel method I receive this object with String1 & String2 deserialized correctly but CopmlexObject1 is null.
How to deal with complex object MvvmCross serialization?
I believe there may be some gremlins in that previous answer - will log as an issue :/
There are other possible routes to achieve this type of complex serializable object navigation still using Json and overriding parts of the framework, but actually I think that it might be better to just use your own BaseViewModel's to do serialization and deserialization - e.g. use serialization code like:
public class BaseViewModel
: MvxViewModel
{
private const string ParameterName = "parameter";
protected void ShowViewModel<TViewModel>(object parameter)
where TViewModel : IMvxViewModel
{
var text = Mvx.Resolve<IMvxJsonConverter>().SerializeObject(parameter);
base.ShowViewModel<TViewModel>(new Dictionary<string, string>()
{
{ParameterName, text}
});
}
}
with deserialization like:
public abstract class BaseViewModel<TInit>
: MvxViewModel
{
public void Init(string parameter)
{
var deserialized = Mvx.Resolve<IMvxJsonConverter>().DeserializeObject<TInit>(parameter);
RealInit(deserialized);
}
protected abstract void RealInit(TInit parameter);
}
then a viewModel like this:
public class FirstViewModel
: BaseViewModel
{
public IMvxCommand Go
{
get
{
return new MvxCommand(() =>
{
var parameter = new A()
{
String1 = "Hello",
String2 = "World",
ComplexObject = new B()
{
Double1 = 42.0,
Double2 = -1
}
};
ShowViewModel<SecondViewModel>(parameter);
});
}
}
}
can navigate to something like:
public class SecondViewModel
: BaseViewModel<A>
{
public A A { get; set; }
protected override void RealInit(A parameter)
{
A = parameter;
}
}
A small addition to Stuart's answer to add type safety:
public class BaseViewModel: MvxViewModel {
protected bool ShowViewModel<TViewModel, TInit>(TInit parameter) where TViewModel: BaseViewModel<TInit> {
var text = Mvx.Resolve<IMvxJsonConverter>().SerializeObject(parameter);
return base.ShowViewModel<TViewModel>(new Dictionary<string, string> { {"parameter", text} });
}
}
public abstract class BaseViewModel<TInit> : BaseViewModel {
public void Init(string parameter)
{
var deserialized = Mvx.Resolve<IMvxJsonConverter>().DeserializeObject<TInit>(parameter);
RealInit(deserialized);
}
protected abstract void RealInit(TInit parameter);
}
ShowViewModel method now takes the same parameter type that the RealInit method instead of an object type. Also, BaseViewModel<TInit> inherits from BaseViewModel so their instances can also call the new ShowViewModel method.
The only drawback is that you have to explicitly specify the parameter type in the call like this:
ShowViewModel<StoreInfoViewModel, Store>(store);

Jackson configuration to write enum as object

When I try to serialize and deserialize a Set<ClassA<?>> of generic objects that look as follows:
public class ClassA<T> {
private ClassB datum;
private T value;
...
}
If that T happens to be an enum, it gets written as a String value. This is fine for serialization, but when I deserialize, it's not possible to know if the String value is an enum or not. Jackson then turns the resulting object into a String and you get a ClassA<String> instead of ClassA<SomeEnumType>.
Is there a configuration in Jackson to have it create some hints that the value is an enum? Or perhaps turn the enum into a JSON object rather then a string value?
Is there a configuration in Jackson to have it create some hints that the value is an enum?
It's possible to deserialize to an enum instance from a matching JSON string value. Or is this somehow not applicable to your situation?
Here is an example.
import java.util.Set;
import java.util.TreeSet;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
public class JacksonFoo
{
public static void main(String[] args) throws Exception
{
ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);
String myEnumJson = mapper.writeValueAsString(MyEnum.MyEnum1);
System.out.println(myEnumJson);
MyEnum myEnum = mapper.readValue(myEnumJson, MyEnum.class);
System.out.println(myEnum);
Set<ClassA<MyEnum>> set = new TreeSet<ClassA<MyEnum>>();
set.add(new ClassA<MyEnum>(new ClassB("bValue7"), MyEnum.MyEnum1));
set.add(new ClassA<MyEnum>(new ClassB("bValue8"), MyEnum.MyEnum2));
String setJson = mapper.writeValueAsString(set);
System.out.println(setJson);
TypeFactory typeFactory = TypeFactory.defaultInstance();
Set<ClassA<MyEnum>> setCopy = mapper.readValue(setJson,
typeFactory.constructCollectionType(Set.class,
typeFactory.constructParametricType(ClassA.class, MyEnum.class)));
System.out.println(setCopy);
}
}
class ClassA<T> implements Comparable<ClassA<T>>
{
ClassB datum;
T value;
ClassA()
{
}
ClassA(ClassB datum, T value)
{
this.datum = datum;
this.value = value;
}
#Override
public int compareTo(ClassA<T> o)
{
return 42;
}
#Override
public String toString()
{
return String.format("ClassA: datum=%s, value=%s", datum, value);
}
}
class ClassB
{
String bValue;
ClassB()
{
}
ClassB(String bValue)
{
this.bValue = bValue;
}
#Override
public String toString()
{
return String.format("ClassB: bValue=%s", bValue);
}
}
enum MyEnum
{
MyEnum1("myEnum1", 1), MyEnum2("myEnum2", 2);
String name;
int id;
MyEnum(String name, int id)
{
this.name = name;
this.id = id;
}
}
Output:
"MyEnum1"
MyEnum1
[{"datum":{"bValue":"bValue7"},"value":"MyEnum1"},{"datum":{"bValue":"bValue8"},"value":"MyEnum2"}]
[ClassA: datum=ClassB: bValue=bValue7, value=MyEnum1, ClassA: datum=ClassB: bValue=bValue8, value=MyEnum2]
If for some reason it's necessary to have enums serialized as POJOs, then it appears custom serialization processing is required. Serializing enums with Jackson