Skip to content

Classes

Taras Koshkin edited this page Jun 7, 2017 · 2 revisions

Sections



First Class!

Java

final public class Product { ... }

final class Product { ... }

public class Product { ... }

abstract public class Product { ... }

public intercace Product { .. }

Kotlin

//by default all classes are final public
class Product { ... }

//same thing as methods, internal is local
internal class Product { ... }

//open will enable you to extend this class (non-final)
open class Product { ... }

//abstract is also open
abstract open class Product { ... }

//interface is the same as in java
interface Product //Notice you don't need brackets if your class is empty

Extending and Implementing

Java

//PresenterActivity is an Abstract Class. 

interface SampleActivityPresenter extends Presenter<SampleActivityView> { }

interface SampleActivityView extends MvpView { }

final class SampleActivity extends PresenterActivity<SampleActivityView, SampleActivityPresenter> implements SampleActivityView { ... }

Kotlin

abstract class PresenterActivity<in V : MvpView, T : Presenter<V>> : AppCompatActivity(), LoaderManager.LoaderCallbacks<T> { }

interface SampleActivityPresenter : Presenter<SampleActivityView>
interface SampleActivityView : MvpView

class SampleActivity : PresenterActivity<SampleActivityView, SampleActivityPresenter>(), SampleActivityView { ... }

Constructors

Java

//Example 1
================================================
//Example of 1 constructor, 1 variable
final public class User {
	private String name;
	
	public User(String name) {
		this.name = name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
}
================================================

//Example 2
================================================
//Example of multiple Variables, multiple constructors
final public class User {	
	private String name;
	private String lastName;
	
	public User(String name) {
		this(name, "");
	}
	
	public User(String name, String lastName) {
		this.name = name;
		this.lastName = lastName;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
}
================================================

Kotlin

//Example 1
================================================
//Example of val and 1 constuctor
class User {
    var name: String

    constructor(name: String) {
        this.name = name
    }
}
//This looks terrible though... let's fix it

//Same as above
class User(val name: String) 
================================================

//Example 2
================================================
//Example of an overload constructor
class User(val name: String, val lastName: String) {
    constructor(name: String) : this(name, "")
}
//But that seems too long right? 

//Overload Class constructors!
class User(val name: String, val lastName: String = "")
//Java won't paly nice with what's above, but there's a solution...

//@JvmOverloads annotation. SUPER USEFUL WHEN CREATING CUSTOM VIEWS
class User @JvmOverloads constructor(val name: String, val lastName: String = "")
================================================

Attributes and Properties

Kotlin

var <propertyName>[: <PropertyType>] [= <property_initializer>]
    [<getter>]
    [<setter>]
    
var allByDefault: Int? // error: explicit initializer required, default getter and setter implied
//To fix it you have to do something like this
var allByDefault: Int? = 0

var initialized = 1 // has type Int, default getter and setter

//custom getter
val isEmpty: Boolean
    get() = this.size == 0
    
var stringRepresentation: String
    get() = this.toString()
    set(value) {
        setDataFromString(value) // parses the string and assigns values to other properties
    }
    
//private setters
var setterVisibility: String = "abc"
    private set // the setter is private and has the default implementation

Lazy and Delegations

Kotlin

// - Synthax for delegates:
// - val/var <property name>: <Type> by <expression>

class Account(val balanceYesterday: Double, val balanceToday: Double) {

	//lazy Delegate
    val changeInBalance: Double by lazy {
        println("computing change in balance")
        balanceToday.minus(balanceYesterday)
    }
    
    //observable Delegate 
    val changeInBalance: Double by Delegates.observable(0.0, {
        property, oldValue, newValue ->
        println("$oldValue -> $newValue")
    })

	//vetoable Delegate
    val changeInBalance: Double by Delegates.vetoable(0.0, {
        property, oldValue, newValue ->
        println("$oldValue -> $newValue")

        if (newValue < 0.toDouble())
            return@vetoable false //new value is rejected when less than 0

        return@vetoable true
    })
}

Singletons

Java

public class Singleton {
	private static final Singleton INSTANCE = new Singleton();
	
	public static Singleton getInstance() {
		return INSTANCE;
	}	
}

Kotlin

object Singleton 

Data Classes

Java

public class User {

    private String name;
    private String lastName;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (name != null ? !name.equals(user.name) : user.name != null) return false;
        return lastName != null ? lastName.equals(user.lastName) : user.lastName == null;

    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
        return result;
    }
}

Kotlin

data class User(val name: String? = "", val lastName: String? = "")

//Added copy method 
fun main() {
	
    val me = User("Taras", "Koshkin")
    val twin = me.copy(name = "Dimitri")
	
}