[JAVA] Kotlin Memorandum-Code Edition (Part 1)

Kotlin Memorandum of Understanding. Continuing from the previous session.

Last time wrote about building an environment.

And many people have written about Java-> Kotlin. When I googled, there was a post from this person first, so I used it as a reference.

Kogarasi's Kotlin starting with Android development

However, just reading it doesn't make sense, so Anyway, you should try it I will write what it is like by touching it.

Make a class

Well, let's create a class first.

-1. Inherit AppCompatActivity -2. Implement View.OnClickListenerOnClickListener

Java


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

}

kotlin


open class MainActivity : AppCompatActivity() , View.OnClickListener {

}

--"open" before class --The description of extends and implements is gone

open modifier

First of all, about "open".

Classes with this open will be inheritable classes. If you do not add open, the class cannot be inherited.

The three visibility of public, private, and protected so far I think it would be good to remember that there are two ways, with or without open.

What is the abstract modifier?

I haven't written this time, but if you want to add the abstract modifier,

kotlin


abstract open class HogeClazz {

}

And put it before open. After checking, it seems that in the case of an abstract class, it can be inherited without adding open.

▼ Abstract class of inheritance source

kotlin


abstract class AbstractSample {
    abstract fun aaa() : Boolean
}

▼ Inheritance class

kotlin


open class ExtendsClazz : AbstractSample() {
    override fun aaa() : Boolean {
        return false;
    }
}

Since it was made with an abstract class, it seems like it would normally be inherited, right?

If you try it, it seems that you can put private in front of class. You can set the visibility so that you can.

So, if there is, the comment that the previous open is incorporated into the three patterns of visibility does not seem to be a good interpretation. open-> can be inherited open-> cannot be inherited I'll just remember it.

Anyway, what is a private class? You have to see how far private classes can be accessed. .. About that later ...

interface What does the interface look like? Let's take a look.

java


public interface IBaseListener {
    void onSuccess();
    void onError(String message, Throwable e);
}

kotlin


interface IBaseListener {
    fun onSuccess()
    fun onError(message: String, e: Throwable)
}

It's almost the same. By the way, you can also add the open modifier to interface. It doesn't seem to matter if you can't implement it without open.

Inner class

The first is the inner class, which does not inherit or implement anything in particular. Let's pass a context and a string as arguments and make it a class that just holds it.

java


    private class InnerClass {
        private Context mContext;
        private String mString;

        public InnerClass(final Context context, final String str) {
            mContext = context;
            mString = str;
        }
    }

kotlin


    private inner class InnerClass(private val mContext: Context, private val mString: String)

It has become much shorter. It seems that you can see each part.

Inner class definition

In Java, it wasn't explicitly stated, but in Kotlin "I will write the inner class! Is it okay? I will write it !!!!" It seems that it is necessary to write "inner class" just to say.

private inner class InnerClass

() After the class name

There is something (). What on earth is this that is not special in Java? Let's compare Java before conversion and Kotlin after conversion.

Java


    private class InnerClass {
        private Context mContext;
        private String mString;

        public InnerClass(final Context context, final String str) {
            mContext = context;
            mString = str;
        }
    }
private inner class InnerClass(private val mContext: Context, private 
val mString: String)

I posted it twice, but in short, it seems that the constructor can be omitted.

However, since this is a constructor that puts values in mContext and mString, isn't it like this? Let's try it.

Without doing anything in the constructor, try adding an initialize method and putting values in mContext and mString there.

java


    private class InnerClass {
        private Context mContext;
        private String mString;

        public InnerClass() {
        }

        public void initialize(final Context context, final String str) {
            mContext = context;
            mString = str;
        }
    }

kotlin


    private inner class InnerClass {
        private var mContext: Context? = null
        private var mString: String? = null

        fun initialize(context: Context, str: String) {
            mContext = context
            mString = str
        }
    }

I see. So, when using the constructor, you can process it with () like this!

... What if you call it super in the constructor? ?? ?? ?? Let's try it.

Let the inner class inherit View and display the one with two constructors in Kotlin.

java


    private class InnerClass extends View {
        private Context mContext;
        private AttributeSet mAttr;

        public InnerClass(Context context) {
            super(context);
            mContext = context;
        }
        
        public InnerClass(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
            mContext = context;
            mAttr = attrs;
        }
    }

kotlin


   private inner class InnerClass : View {
        private var mContext: Context? = null
        private val mAttr: AttributeSet

        constructor(context: Context) : super(context) {
            mContext = context
        }

        constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
            mContext = context
            mAttr = attrs
        }
    }

Oh! !! !!

You write "constructor". Calling super after the ":" It seems to write other processing in parentheses.

It seems that you have a different habit than before. This seems to need to be remembered.

By the way, when there was only one constructor, the description was different.

In one case

kotlin


private inner class InnerClass(private val mContext: Context) : View(mContext) {
}

It seems that the description of the constructor can be omitted.

// Addendum I was a little worried and tried to find out, but this was not limited to the inner class. .. ..

So this statement applies to any regular class.

kotlin


open class HogeClass(private val mContext: Context) : View(mContext) {
}

The same description applies when a class that inherits View is generated, as in.

Well, earlier

After trying it, it seems that private can be added before class.

I mentioned earlier, but maybe it's probably the visibility provided for this inner class. You may not understand this point unless you go a little further. .. ..

Variables and constants

Let's look at variables and constants.

java


    private static final int TEISU_INT = 0;
    private static final String TEISU_STRING = "hoge";
    private Context mContext;
    private View mView;

kotlin


    private val mContext: Context? = null
    private val mView: View? = null

    companion object {
        private val TEISU_INT = 0
        private val TEISU_STRING = "hoge"
    }

variable

First, let's explain the variables.

private val hoge: String? = null

val and var

private ** val ** ← this guy

This has the same role as the final modifier in Java.

java


final String strHoge = "hoge";
strHoge = "huga";★ Compile error because it cannot be assigned

String strHuga = "hoge";
strHuga = "huga";★ Can be substituted

This is the case with Kotlin.

kotlin


val strHoge: String? = "hoge";
strHoge = "huga";★ Compile error because it cannot be assigned

var strHuga: String? = "hoge";
strHuga = "huga";★ Can be substituted

It's not as much as writing. ..

Object definition

hoge **: String ** ← This guy

This is the part. Since the order of specification is opposite to that of Java, every time I start writing Kotlin "Oh ... I've done it again" It will be w

Until now, object specification-> variable name was changed to variable name first. This is because Kotlin no longer requires you to specify an object.

In other words, it is now possible to define with type inference. for that reason

kotlin


var hoge = null

Of course it is OK. However, for those who have been doing Java until now, this is really hard. I don't know what to put in or what to use. If hoge is a variable name, it's superfluous.

So I don't know how to use it in the future, but normally

  1. var or val
  2. Variable name
  3. Specify the object

I think it's okay to write it like this.

"?" Behind the object

: String **? ** ← This guy

What is this?

I interpreted it as the same as NonNull annotation and Nullable annotation in Java. For the time being, it is the behavior with and without "?".

kotlin


var str1: String?
str =null ★ What is this? Since it is Nullable, null assignment is OK

var str2: String
str =null ★ What is this? Null assignment NG because it is None Null

this? I think that the designation corresponds to what the swift developer calls "optional type" and "non-optional type".

It may be familiar to those who are doing swift, but it may take some time to accept it because it is too unfamiliar to those who have been doing Java for Android development all the time. Regarding the handling of this area, I would like to write a separate article and organize it properly.

constant

Next is a constant. The writing style has changed drastically, so I think it's enough to learn how to specify it for the time being. I will write the code again.

Constant definition in kotlin


    companion object {
        private val TEISU_INT = 0
        private val TEISU_STRING = "hoge"
    }

I translated it with companion. .. Does it feel like "each other"? ?? image.png

By the way, if it is private, it cannot be referenced from other classes, of course. It was possible to refer to it without private. It's treated as public. I couldn't specify protected because it seems that the visibility is lost.

Constant definition in kotlin


    companion object {
        private val TEISU_INT =0 ← Cannot be referenced from other classes
        val TEISU_STRING = "hoge"← Can be referenced from other classes
    }

For the time being, I created a class, then defined variables, and so on.

Ah, if you add "; (semicolon)" at the end of the instruction, a compile error will occur, so I think you will add it as a habit, but be careful.

I'll write a lot of other things, but I'll leave it here for now.

Also, if you want to see a sample about kotlin, you may want to see it here. https://try.kotlinlang.org/

Recommended Posts

Kotlin Memorandum-Code Edition (Part 1)
Memo: Kotlin + Room + RecyclerView + DataBinding (Part 2)
Kotlin Class part.2 to send to Java developers